<!DOCTYPE html>
<html lang="en">
{{> head}}

<body>
    <div class="i_w center">
        <div>
            <crowdin-card is-shadowed is-padding-lg class="login">
                <img alt='{{ name }} logo' src='logo.png' />
                <crowdin-h4 id="integration-name">{{ name }}</crowdin-h4>
                <div class="inputs">
                    {{#each loginFields}}
                        {{#if key}}
                            {{#in type "checkbox select textarea file notice"}}
                                {{#ifeq type "checkbox"}}
                                    <crowdin-checkbox
                                        id="{{key}}"
                                        label="{{label}}"
                                        value="false"
                                        use-switch
                                        {{#if helpText}}
                                            help-text="{{helpText}}"
                                        {{/if}}
                                        {{#if helpTextHtml}}
                                            help-text-html="{{helpTextHtml}}"
                                        {{/if}}
                                        {{#ifeq defaultValue true}}
                                            checked="{{defaultValue}}"
                                        {{/ifeq}}
                                        {{#if dependencySettings}}
                                            data-dependency="{{dependencySettings}}"
                                        {{/if}}
                                    >
                                    </crowdin-checkbox>
                                {{/ifeq}}
                                {{#ifeq type "select"}}
                                    <crowdin-select
                                        {{#if isMulti}}
                                            is-multi
                                            close-on-select="false"
                                        {{/if}}
                                        {{#if isSearchable}}
                                            is-searchable
                                        {{/if}}
                                        id="{{key}}"
                                        label="{{label}}"
                                        {{#if helpText}}
                                            help-text="{{helpText}}"
                                        {{/if}}
                                        {{#if helpTextHtml}}
                                            help-text-html="{{helpTextHtml}}"
                                        {{/if}}
                                        {{#if dependencySettings}}
                                            data-dependency="{{dependencySettings}}"
                                        {{/if}}
                                    >
                                        {{#each options}}
                                            <option {{#ifeq ../defaultValue value}} selected {{/ifeq}} value="{{value}}">{{label}}</option>
                                        {{/each}}
                                    </crowdin-select>
                                {{/ifeq}}
                                {{#ifeq type "textarea"}}
                                    <crowdin-textarea
                                        id="{{key}}"
                                        label="{{label}}"
                                        {{#if helpText}}
                                            help-text="{{helpText}}"
                                        {{/if}}
                                        {{#if helpTextHtml}}
                                            help-text-html="{{helpTextHtml}}"
                                        {{/if}}
                                        {{#if dependencySettings}}
                                            data-dependency="{{dependencySettings}}"
                                        {{/if}}
                                        value="{{#if defaultValue}}{{defaultValue}}{{/if}}">
                                    </crowdin-textarea>
                                {{/ifeq}}
                                {{#ifeq type "notice"}}
                                    <crowdin-alert
                                        {{#if noticeType}}
                                            type="{{noticeType}}"
                                        {{/if}}
                                        {{#if label}}
                                            title="{{label}}"
                                        {{/if}}
                                        {{#if noIcon}}
                                            no-icon="{{noIcon}}"
                                        {{/if}}
                                        {{#if dependencySettings}}
                                            data-dependency="{{dependencySettings}}"
                                        {{/if}}
                                    >
                                        {{{helpText}}}
                                    </crowdin-alert>
                                {{/ifeq}}
                                {{#ifeq type "file"}}
                                    <div class="file-field">
                                        {{#if helpText}}<div class="help-text">{{helpText}}</div>{{/if}}
                                        {{#if helpTextHtml}}<div class="help-text">{{helpTextHtml}}</div>{{/if}}
                                        <div class="upload">
                                            <crowdin-button outlined onclick="uploadFiles('{{key}}');">{{label}}</crowdin-button>
                                            <textarea hidden id="{{key}}"></textarea>
                                            <input
                                                id="store_{{key}}"
                                                data-id="{{key}}"
                                                {{#if accept}}
                                                    accept="{{accept}}"
                                                {{/if}}
                                                onchange="readFileData(event)"
                                                hidden
                                                type="{{type}}"
                                            >
                                            <div class="uploaded-file"><i>No file</i></div>
                                        </div>
                                    </div>
                                {{/ifeq}}
                            {{else}}
                                <crowdin-input
                                    id="{{key}}"
                                    label="{{label}}"
                                    {{#if helpText}}
                                        help-text="{{helpText}}"
                                    {{/if}}
                                    {{#if helpTextHtml}}
                                        help-text-html="{{helpTextHtml}}"
                                    {{/if}}
                                    {{#if type}}
                                        type="{{type}}"
                                    {{/if}}
                                    {{#if dependencySettings}}
                                        data-dependency="{{dependencySettings}}"
                                    {{/if}}
                                    value="{{#if defaultValue}}{{defaultValue}}{{/if}}">
                                </crowdin-input>
                            {{/in}}
                        {{else}}
                             {{#if labelHtml}}
                                 <crowdin-p
                                     {{#if dependencySettings}}
                                        data-dependency="{{dependencySettings}}"
                                     {{/if}}
                                 >
                                    {{{labelHtml}}}
                                 </crowdin-p>
                             {{else}}
                                 <crowdin-p
                                     {{#if dependencySettings}}
                                        data-dependency="{{dependencySettings}}"
                                     {{/if}}
                                 >
                                    {{label}}
                                 </crowdin-p>
                             {{/if}}
                        {{/if}}
                        <div
                            style="padding: 8px"
                            {{#if dependencySettings}}
                                data-dependency="{{dependencySettings}}"
                            {{/if}}
                        ></div>
                    {{/each}}
                    </div>
                <crowdin-button
                    id="login-button"
                    outlined icon-after="arrow_forward"
                    {{#if oauthLogin}}
                    onclick="oauthLogin()"
                    {{else}}
                    onclick="integrationLogin()"
                    {{/if}}
                >
                    Log In With {{ name }}
                </crowdin-button>
            </crowdin-card>
        </div>
    </div>
    <crowdin-toasts></crowdin-toasts>
</body>
<script type="text/javascript">
    const loginButton = document.querySelector('#login-button');
    let refreshIntervalId;

    function oauthLogin() {
        {{#if oauthUrl}}
        const url = '{{{ oauthUrl }}}';
        {{else}}
        const url = undefined;
        {{/if}}
        if (url) {
            openOAuthPopup(url);
            return;
        }
        loginButton.setAttribute('disabled', true);
        loginButton.setAttribute('is-loading', true);
        checkOrigin()
            .then(queryParams =>
                fetch(`api/oauth-url${queryParams}`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ loginForm: getLoginForm() })
                })
            )
            .then(checkResponse)
            .then(res => openOAuthPopup(res.url))
            .catch(e => {
                loginButton.setAttribute('disabled', false);
                loginButton.setAttribute('is-loading', false);
                catchRejection(e, 'Can\'t get oauth token');
            });
    }

    function openOAuthPopup(url) {
        {{#if oauthMode}}
        const oauthMode = '{{{ oauthMode }}}';
        {{else}}
        const oauthMode = undefined;
        {{/if}}
        const oauthWindow = window.open(url, '{{ name }}', 'location=0,status=0,width=800,height=400');

        if (oauthMode === 'polling') {
            if (refreshIntervalId) {
                clearInterval(refreshIntervalId);
            }
            refreshIntervalId = setInterval(() => 
                checkOrigin()
                    .then(queryParams =>
                        fetch(`api/oauth-polling${queryParams}`, {
                            method: 'POST',
                        })
                    )
                    .then(checkResponse)
                    .then(res => {
                        if (res.oauthCreds) {
                            integrationLogin({
                                refreshToken: res.oauthCreds.refreshToken,
                                accessToken: res.oauthCreds.accessToken,
                                expireIn: res.oauthCreds.expireIn,
                                timestamp: res.oauthCreds.timestamp
                            });
                            if (refreshIntervalId) {
                                clearInterval(refreshIntervalId);
                            }
                        }
                    }), 2000);
            return;
        }

        postPromises['oauth_popup'] = {
            resolve: (data) => {
                if (data.error) {
                    showToast(data.error);
                    return;
                }
                integrationLogin({
                    refreshToken: data.refreshToken,
                    accessToken: data.accessToken,
                    expireIn: data.expireIn,
                    timestamp: data.timestamp
                });
            }
        }
    }

    function integrationLogin(oauthCredentials) {
        const credentials = oauthCredentials || getLoginForm();
        loginButton.setAttribute('disabled', true);
        loginButton.setAttribute('is-loading', true);
        checkOrigin()
            .then(queryParams =>
                fetch(`api/login${queryParams}`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ credentials })
                })
            )
            .then(checkResponse)
            .then(localStorage.removeItem('revised_{{name}}'))
            .then(reloadLocation)
            .catch(e => {
                loginButton.setAttribute('disabled', false);
                loginButton.setAttribute('is-loading', false);
                catchRejection(e, 'Credentials are not stored');
            });
    }

    function getLoginForm() {
        return {
            {{#each loginFields}}
                {{#if key}}
                    {{#ifeq type "checkbox"}}
                        '{{key}}': !!document.querySelector('#{{key}}').checked,
                    {{else}}
                        '{{key}}': document.querySelector('#{{key}}').getAttribute('value') || document.querySelector('#{{key}}').value,
                    {{/ifeq}}
                {{/if}}
            {{/each}}
        };
    }

    function uploadFiles(id) {
        const input = document.querySelector(`#store_${id}`);
        input.value = '';
        input.click();
    }

    function readFileData(event) {
        const reader = new FileReader();
        const identifier = event.target.getAttribute('data-id');
        const fileName = document.querySelector('.uploaded-file');
        const input = document.querySelector(`#${identifier}`);
        const file = event.target.files[0];
        fileName.innerText = file.name;

        reader.onloadstart = function() {
            loginButton.setAttribute('disabled', true);
            loginButton.setAttribute('is-loading', true);
        };
        reader.onloadend = function() {
            loginButton.setAttribute('disabled', false);
            loginButton.setAttribute('is-loading', false);
        };

        reader.onload = () => {
            input.value = reader.result;
        };
        reader.readAsText(file);
    }

</script>

</html>
