{% extends '_base_only_content.html' %}
{% load static %}
{% load i18n %}
{% load bootstrap3 %}
{% block custom_head_css_js %}
    <style>
        .margin-bottom {
            margin-bottom: 15px;
        }

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

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

        .btn-challenge {
            width: 110px !important;
            height: 100%;
            vertical-align: top;
        }

        .scrollable-menu {
            height: auto;
            max-height: 18rem;
            overflow-x: hidden;
        }

        .input-group {
            .input-group-btn .btn-secondary {
                color: #464a4c;
                background-color: #eceeef;
            }
        }
    </style>
{% endblock %}
{% block html_title %}{% trans 'Forgot password' %}{% endblock %}
{% block title %} {% trans 'Forgot password' %}?{% endblock %}

{% block content %}
    <p id="validate-email-tip" class="validate-field">
        {% trans 'Input your email account, that will send a email to your' %}
    </p>
    <p id="validate-sms-tip" class="validate-field">
        {% trans 'Enter your mobile number and a verification code will be sent to your phone' %}
    </p>

    {% if 'code' in form.errors %}
        <p class="red-fonts">{{ form.code.errors.as_text }}</p>
    {% endif %}

    <div class="row">
        <div class="col-sm-12">
            <select id="validate-backend-select" name="validate-backend_type"
                    class="form-control select-con margin-bottom" onchange="selectChange(this.value)">
                {% for backend in validate_backends %}
                    <option value="{{ backend.value }}" {% if not backend.is_active %} disabled {% endif %}>
                        {{ backend.name }}
                    </option>
                {% endfor %}
            </select>
            <form role="form" class="form-horizontal" action="" method="post">
                {% csrf_token %}
                {% bootstrap_field form.form_type layout="horizontal" %}
                <div id="validate-email" class="validate-field margin-bottom">
                    <input type="email" id="email" name="email" class="form-control input-style"
                           placeholder="{% trans 'Email account' %}" value="{{ email }}">
                </div>
                <div id="validate-sms" class="validate-field margin-bottom">
                    <div class="input-group">
                        <div class="input-group-btn">
                            <button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown"
                                    aria-haspopup="true" aria-expanded="false">
                                <span class="country-code-value">+86</span>
                            </button>
                            <ul class="dropdown-menu scrollable-menu">
                                <input type="hidden" name="country_code" id="country_code" value="+86">
                                {% for country in countries %}
                                    <li>
                                        <a href="#" class="dropdown-item d-flex justify-content-between">
                                            <span class="country-name text-left">{{ country.name }}</span>
                                            <span class="country-code">{{ country.value }}</span>
                                        </a>
                                    </li>
                                {% endfor %}
                            </ul>
                        </div>
                        <input type="tel" id="sms" name="sms" class="form-control input-style"
                               placeholder="{% trans 'Mobile number' %}" value="{{ sms }}">
                    </div>
                </div>
                <div class="margin-bottom challenge-required">
                    <input type="text" id="code" name="code" class="form-control input-style"
                           placeholder="{% trans 'Verify code' %}">
                    <button class="btn btn-primary full-width btn-challenge"
                            type='button' onclick="sendChallengeCode(this)">
                        {% trans 'Send' %}
                    </button>
                </div>
                <div class="margin-bottom">
                    <button type="submit" class="btn btn-primary block full-width m-b">{% trans 'Submit' %}</button>
                </div>
            </form>
        </div>
    </div>
    <script>
        $(function () {
            const validateSelectRef = $('#validate-backend-select')
            const formType = $('input[name="form_type"]').val()
            validateSelectRef.val(formType)
            if (formType !== null) {
                selectChange(formType);
            }
        })

        $(".dropdown-menu li a").click(function (evt) {
            const inputGroup = $('.input-group');
            const inputGroupAddon = inputGroup.find('.country-code-value');
            const selectedCountry = $(evt.target).closest('li');
            const selectedCountryCode = selectedCountry.find('.country-code').html();
            $('#country_code').val(selectedCountryCode)
            inputGroupAddon.html(selectedCountryCode)
        });


        function getQueryString(name) {
            const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            const r = window.location.search.substr(1).match(reg);
            if (r !== null)
                return unescape(r[2])
            return null
        }

        function selectChange(name) {
            $('.validate-field').hide()
            $('#validate-' + name).show()
            $('#validate-' + name + '-tip').show()
            $('input[name="form_type"]').attr('value', name)
        }

        function sendChallengeCode(currentBtn) {
            let time = 60;
            const token = getQueryString('token')
            const url = "{% url 'api-auth:reset-password-code' %}" + "?token=" + token;

            const formType = $('input[name="form_type"]').val()
            const email = $('#email').val()
            let sms = $('#sms').val();
            const errMsg = "{% trans 'The {} cannot be empty' %}"

            if (formType === 'sms') {
                if (sms === "") {
                    toastr.error(errMsg.replace('{}', "{% trans 'SMS' %}"))
                    return
                }
            } else {
                if (email === "") {
                    toastr.error(errMsg.replace('{}', "{% trans 'Email' %}"))
                    return
                }
            }
            sms = $(".input-group .country-code-value").html() + sms
            const data = {
                form_type: formType, email: email, sms: sms,
            }

            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)
            }

            requestApi({
                url: url,
                method: "POST",
                body: JSON.stringify(data),
                success: onSuccess,
                success_message: "{% trans 'The verification code has been sent' %}",
                flash_message: true
            })
        }
    </script>
{% endblock %}

