{% load i18n %}
{% load static %}

<select id="mfa-select" name="mfa_type" class="form-control select-con" autocomplete="off"
        onchange="selectChange(this.value)"
>
    {% for backend in mfa_backends %}
    <option value="{{ backend.name }}"
            data-needs-bind="{% if backend.name == 'otp' and not backend.is_active %}true{% else %}false{% endif %}"
            {% if not backend.is_active and backend.name != 'otp' %} disabled {% endif %}
    >
        {{ backend.display_name }}
    </option>
    {% endfor %}
</select>
<div class="mfa-div">
    {% for backend in mfa_backends %}
    <div id="mfa-{{ backend.name }}" class="mfa-field
            {% if backend.challenge_required %}challenge-required{% endif %}"
         style="display: none"
    >
        {% if backend.name == 'otp' and not backend.is_active %}
        <small class="text-muted">{% trans 'Enable OTP' %}</small>
        {% elif backend.has_code %}
        <input type="text" class="form-control input-style"
               placeholder="{{ backend.placeholder }}"
               autocomplete="off"
        >
        {% if backend.challenge_required %}
        <button class="btn btn-primary full-width btn-challenge"
                type='button' onclick="sendChallengeCode(this)"
        >
            {% trans 'Send' %}
        </button>
        {% endif %}
        {% endif %}
    </div>
    {% endfor %}
</div>

<style>
    .input-style {
        width: 100%;
        display: inline-block;
    }

    .challenge-required .input-style {
        width: calc(100% - 104px);
        display: inline-block;
    }

    .btn-challenge {
        width: 100px !important;
        height: 100%;
        vertical-align: top;
    }
</style>
<script>
    const preferMFAKey = 'mfaPrefer'

    function getMFAOption(selectRef, value) {
        let optionRef = null
        $(selectRef).find('option').each(function () {
            if (this.value === value) {
                optionRef = this
                return false
            }
        })
        return optionRef
    }

    function optionNeedsBind(optionRef) {
        return optionRef && optionRef.dataset.needsBind === 'true'
    }

    function getFirstReadyMFAOption(selectRef) {
        let optionRef = null
        $(selectRef).find('option').each(function () {
            if (!this.disabled && !optionNeedsBind(this)) {
                optionRef = this
                return false
            }
        })
        return optionRef
    }

    $(document).ready(function () {
        const mfaSelectRef = document.getElementById('mfa-select');
        const preferMFA = localStorage.getItem(preferMFAKey);
        const preferMFAOption = getMFAOption(mfaSelectRef, preferMFA)

        if (preferMFAOption && !preferMFAOption.disabled && !optionNeedsBind(preferMFAOption)) {
            mfaSelectRef.value = preferMFA;
        }

        let mfaSelect = mfaSelectRef.value;
        const selectedOption = getMFAOption(mfaSelectRef, mfaSelect)
        if (optionNeedsBind(selectedOption)) {
            const readyOption = getFirstReadyMFAOption(mfaSelectRef)
            if (readyOption) {
                mfaSelectRef.value = readyOption.value
                mfaSelect = readyOption.value
            }
        }

        if (mfaSelect !== null) {
            selectChange(mfaSelect, true);
        }
    })

    function selectChange(name, onLoad) {
        $('.mfa-field').hide()
        $('#mfa-' + name).show()
        if (!onLoad) {
            localStorage.setItem(preferMFAKey, name)
        }

        $('.input-style').each(function (i, ele) {
            $(ele).prop('disabled', true).removeAttr('name')
        })

        const currentMFAInputRef = $('#mfa-' + name + ' .input-style')
        currentMFAInputRef.prop('disabled', false).attr('name', 'code')

        // 登录页时，不应该默认focus
        const usernameRef = $('input[name="username"]')
        if (!usernameRef || usernameRef.length === 0) {
            setTimeout(() => {
                currentMFAInputRef.focus()
            })
        }
    }

    function sendChallengeCode(currentBtn) {
        let time = 60;
        const url = "{% url 'api-auth:mfa-select' %}";
        const data = {
            type: $("#mfa-select").val(),
            username: $('input[name="username"]').val()
        };

        function onSuccess() {
            const originBtnText = currentBtn.innerHTML;
            currentBtn.disabled = true

            const interval = setInterval(function () {
                currentBtn.innerHTML = `{% trans 'Wait: ' %} ${time}`;
                time -= 1

                if (time === 0) {
                    currentBtn.innerHTML = originBtnText
                    currentBtn.disabled = false
                    clearInterval(interval)
                }
            }, 1000)
            setTimeout(function () {
                toastr.success("{% trans 'The verification code has been sent' %}");
            })
        }

        function onError(responseText, responseJson, status) {
            setTimeout(function () {
                toastr.error(responseJson.detail || responseJson.error);
            });
        };

        requestApi({
            url: url,
            method: "POST",
            body: JSON.stringify(data),
            success: onSuccess,
            error: onError,
            flash_message: false
        })
    }
</script>
