import { Controller } from 'stimulus';
import Inputmask from "inputmask";
const loader = require("./../components/loader.js");
const validator = require("./../components/validator.js");
const helper = require("./../components/helper.js");

/*
 * This is an example Stimulus controller!
 *
 * Any element with a data-controller="resetPassword" attribute will cause
 * this controller to be executed. The name "resetPassword" comes from the filename:
 * resetPassword_controller.js -> "resetPassword"
 *
 * Delete this file or adapt it for your use!
 */
export default class extends Controller {
    connect() {
        loader.loadSDK('resetPassword')
        let resetPasswordSmsCode = true;
        var popup = document.getElementById('popup');
        
        if (location.hash == '#recovery' && popup.dataset.recovery == 'true') {
            popup.dataset.recovery = false;
            renderForm(window.webSDK);
        } else {
        	var element = this.element
    		element.addEventListener('click', function() {
                renderForm(window.webSDK);
    		});
        }

        function renderForm(webSDK) {
            var popup = document.getElementById('popup');
            popup.querySelector('.modal-title').innerHTML = "Восстановление пароля";
            var popupBody = popup.querySelector('#popup-body');
            popupBody.innerHTML = "";

            if (typeof $(popup).modal !== 'undefined') {
                $(popup).modal('show');
            }

            var div = document.createElement('div');
            div.classList = 'form-group';

            if (resetPasswordSmsCode) {
                var label = document.createElement('label');
                label.setAttribute('for' , 'login-forget');
                label.innerHTML = 'Телефон пользователя:';
                div.append(label);

                var input = document.createElement('input');
                input.classList = "form-control";
                input.id = "login-forget";
                input.type = "phone";
                input.autocomplete = "phone";
                div.append(input);
                
                var im = new Inputmask({mask: "7(899)999-99-99",definitions: {'8': {validator: "[9]"}}});
                im.mask(input);
            } else {
                var label = document.createElement('label');
                label.setAttribute('for' , 'login-forget');
                label.innerHTML = 'E-mail пользователя:';
                div.append(label);

                var input = document.createElement('input');
                input.classList = "form-control";
                input.id = "login-forget";
                input.autocomplete = "email";
                input.type = "email";
                div.append(input);
            }

            var validUsername = document.createElement('div');
            validUsername.classList = "msg-valid valid-login-forget";
            div.append(validUsername);
            
            if (resetPasswordSmsCode) {
                var p = document.createElement('p');
                p.innerHTML = "На Ваш номер телефона будет отправлен код для восстановления пароля."
                popupBody.append(p);

            } else {
                var p = document.createElement('p');
                p.innerHTML = "На Вашу электронную почту будет отправлен код для восстановления пароля."
                popupBody.append(p);
            }

            var msg = document.createElement('div');
            msg.classList = 'd-none msg';
            msg.innerHTML = '';
            popupBody.append(div);
            popupBody.append(msg);

            var div = document.createElement('div');
            div.classList = 'form-group';

            var recaptcha = document.createElement('div');
            recaptcha.id = "smart-captcha";
            recaptcha.dataset.controller = "smartCaptcha";
            div.append(recaptcha);

            var validRecaptcha = document.createElement('div');
            validRecaptcha.classList = "msg-valid valid-captcha";
            div.append(validRecaptcha);
            popupBody.append(div);
                    
            var button = document.createElement('button');
            button.classList = "btn btn-primary";
            button.innerHTML = "Восстановить"
            button.addEventListener('click', function () {

                loader.btnLoader(button, true);
                resetPassword(webSDK, popup)                
            });

            var footer = document.createElement('div');
            footer.classList = 'modal-footer px-0';

            footer.append(button);
            popupBody.append(footer);
        };

        function resetPassword(webSDK, popup) {
            var popupBody = popup.querySelector('#popup-body');
            
            var valid, invalid = false;
            if (resetPasswordSmsCode) {
                valid = validator.checkPhone(
                    document.getElementById('login-forget'), 
                    document.querySelector(`.valid-login-forget`)
                );

                var login = document.getElementById('login-forget').value.replace(/[^\w\s!?]/g,'');
            } else {
                valid = validator.checkEmail(
                    document.getElementById('login-forget'), 
                    document.querySelector(`.valid-login-forget`)
                );

                var login = document.getElementById('login-forget').value;
            }
            

            if (valid) {
                invalid = valid
            }

            valid = validator.checkSmartCaptcha(
                window.smartCaptcha.getResponse(), 
                document.querySelector('.valid-captcha')
            );
            
            if (valid) {
                invalid = valid
            }

            if (invalid) {
                loader.btnLoader(popupBody.querySelector('button'), false);
                return false;
            }

            $.ajax({
                async : false,
                method: "POST",
                crossDomain: true,
                url: helper.getHostname() + "/forget",
                contentType: "application/x-www-form-urlencoded",
                dataType: "json",
                data: {
                    token: popupBody.dataset.csrf,
                    login: login
                },
                success(response) {
                    window.webSDK.recoveryInit({
                        'login': login,
                        'captcha': window.smartCaptcha.getResponse()
                    }).then(function (resolve) {
                        renderFormConfirm(webSDK, popup, resolve, response);
                    }).catch(function (e) {
                        helper.sendRequest({
                            data: {'error': e, method: 'recoveryInit'}
                        }, helper.getHostname() + '/api/log', "POST");
                        
                        window.smartCaptcha.reset();
                        
                        if (e.data?.errors?.captcha) {
                            document.querySelector('.valid-captcha').innerText = e.data?.errors?.captcha?.[0];
                        }

                        loader.btnLoader(popupBody.querySelector('button'), false);

                        if (e.data?.message) {
                            var msg = popupBody.querySelector('.msg');
                            msg.classList = 'alert alert-danger';
                            msg.innerHTML = e.data.message;
                        }
                    });
                }
            });
        };

        function renderFormConfirm(webSDK, popup, resolve, forget) {
            var popupBody = popup.querySelector('#popup-body');
            popupBody.innerHTML = "";

            var message = document.createElement('p');
            message.innerHTML = resolve.data.message;
            popupBody.append(message);

            var div = document.createElement('div');
            div.classList = 'form-group';

            var label = document.createElement('label');
            label.setAttribute('for' , 'forget-code');
            label.innerHTML = 'Код подтверждения:';
            div.append(label);

            var input = document.createElement('input');
            input.classList = "form-control";
            input.id = "forget-code";
            input.autocomplete = "one-time-code";
            input.autocorrect = "off";
            input.spellcheck = "off";
            input.type = "text";
            div.append(input);

            var divValidCode = document.createElement('div');
            divValidCode.classList = "msg-valid valid-code";
            div.append(divValidCode);
            popupBody.append(div);

            var div = document.createElement('div');
            div.classList = 'form-group';

            var label = document.createElement('label');
            label.setAttribute('for' , 'forget-passwd');
            label.innerHTML = 'Новый пароль:';
            div.append(label);

            var input = document.createElement('input');
            input.classList = "form-control";
            input.id = "forget-passwd";
            input.autocomplete = "new-password";
            input.type = "password";
            div.append(input);

            var divValidPass = document.createElement('div');
            divValidPass.classList = "msg-valid valid-password";
            divValidPass.innerHTML = "не менее 7 символов";
            div.append(divValidPass);
            popupBody.append(div);

            var msg = document.createElement('div');
            msg.classList = 'd-none alert alert-danger';
            msg.innerHTML = '';
            popupBody.append(msg);

            var button = document.createElement('button');
            button.classList = "btn btn-primary";
            button.innerHTML = " Сохранить изменения";
            button.addEventListener('click', function () {
                popupBody.querySelectorAll('.msg-valid').forEach(function(el) {
                    el.innerHTML = '';
                });

                var invalid = false;
                var forgetCode = document.getElementById('forget-code').value;

                if (forgetCode === '') {
                    popupBody.querySelector('.valid-code')
                            .innerHTML = '<span class="text-danger">поле не может быть пустым</span>';
                        popupBody.querySelector('#forget-code').classList.add('is-invalid');
                        popupBody.querySelector('#forget-code').classList.remove('is-valid');
                        invalid = true;     
                } else {
                    popupBody.querySelector('#forget-code').classList.add('is-valid');
                    popupBody.querySelector('#forget-code').classList.remove('is-invalid');   
                }

                var forgetPasswd = document.getElementById('forget-passwd').value;

                if (forgetPasswd.length < 6 || /^[\u0400-\u04FF]+$/.test(forgetPasswd)) {
                    invalid = true;
                    
                    if (/^[\u0400-\u04FF]+$/.test(forgetPasswd)) {
                        popupBody.querySelector('.valid-password')
                            .innerHTML = '<span class="text-danger">поле не должно содержать кириллицы</span>';
                        popupBody.querySelector('#forget-passwd').classList.add('is-invalid');
                        popupBody.querySelector('#forget-passwd').classList.remove('is-valid');
                    } else {
                        popupBody.querySelector('.valid-password')
                            .innerHTML = '<span class="text-danger">не менее 7 символов</span>';
                        popupBody.querySelector('#forget-passwd').classList.add('is-invalid');
                        popupBody.querySelector('#forget-passwd').classList.remove('is-valid');
                    }
                } else {
                    popupBody.querySelector('#forget-passwd').classList.add('is-valid');
                    popupBody.querySelector('#forget-passwd').classList.remove('is-invalid');
                }

                if (invalid) {
                    return false;
                }

                window.webSDK.recoveryComplete({
                    'pwdToken': resolve.data.pwdToken,
                    'password': forgetPasswd,
                    'code': document.getElementById('forget-code').value
                }).then(function (result) {
                    if (result.data.errors) {
                        if (result.data.errors.code) {
                            popupBody.querySelector('.valid-code').innerHTML = `<span class="text-danger">
                                ${result.data.errors.code}</span>`;
                        }

                        return false;
                    }

                    popupBody.innerHTML = '';                    
                    var msg = document.createElement('div');
                    msg.classList = 'alert alert-success';
                    msg.innerHTML = result.data.message;
                    popupBody.append(msg);

                    $.ajax({
                        method: "POST",
                        crossDomain: true,
                        url: helper.getHostname() + "/forget",
                        contentType: "application/x-www-form-urlencoded",
                        dataType: "json",
                        data: {
                            token: popupBody.dataset.csrf,
                            uid: forget.data.uid,
                            password: forgetPasswd
                        },
                        success(response) {
                            if (response.data.success == true) {
                                var parser = document.createElement('a');
                                parser.href = response.data.redirect;
                                window.location.replace(document.location.origin + parser.pathname + parser.search);
                            }
                        }
                    });
                }).catch(function (e) {
                    helper.sendRequest({
                        data: {'error': e, method: 'recoveryComplete'}
                    }, helper.getHostname() + '/api/log', "POST");
                    
                    if (e.data && e.data.error) {
                        msg.innerHTML = e.data.error
                        msg.classList.remove('d-none');
                    }
                });
            });

            var footer = document.createElement('div');
            footer.classList = 'modal-footer';
            footer.append(button);
            popupBody.append(footer);
        };
    }
}





   








