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

export default class extends Controller {
    connect() {
        loader.loadSDK('registration')
        var registerWrap = this.element;
        var licenseLink = helper.getLicenseLink(Cookies.get('region'));
        helper.renderCapcha(registerWrap.querySelector('.d-capcha-start'));
        registerWrap.querySelectorAll('.license').forEach(function(el) {
            /* политика */
            var div = document.createElement('div');
            div.classList = 'form-group';

            var formCheck = document.createElement('div');
            formCheck.classList = 'form-check';
            div.append(formCheck);

            var accept = document.createElement('input');
            accept.classList = "form-check-input";
            accept.id = "accept";
            accept.checked = false;
            accept.type = "checkbox";
            formCheck.append(accept);

            var license = helper.getLicenseLink(Cookies.get('region'));
            var label = document.createElement('label');
            label.setAttribute('for' , 'accept');
            label.innerHTML = `ознакомлен(а) <a class="underline" href="${licenseLink}" target="_blank">с условиями политики в отношении обработки персональных данных</a>`;
            
            formCheck.append(label);
            
            var validAccept = document.createElement('div');
            validAccept.classList = 'msg-valid valid-accept';
            div.append(validAccept);

            el.append(div)

            /* согласие */

            var formCheck = document.createElement('div');
            formCheck.classList = 'form-check';
            div.append(formCheck);

            var acceptPerson = document.createElement('input');
            acceptPerson.classList = "form-check-input";
            acceptPerson.id = "acceptPerson";
            acceptPerson.checked = false;
            acceptPerson.type = "checkbox";
            formCheck.append(acceptPerson);

            var licensePerson = helper.getLicensePersonLink();
            var labelPerson = document.createElement('label');
            labelPerson.setAttribute('for' , 'acceptPerson');
            labelPerson.innerHTML = `даю согласие <a class="underline" href="${licensePerson}" target="_blank">на обработку персональных данных</a>`;
            
            formCheck.append(labelPerson);
            
            var validAcceptPerson = document.createElement('div');
            validAcceptPerson.classList = 'msg-valid valid-acceptPerson';
            div.append(validAcceptPerson);

            el.append(div)
        });
    }

    btnBack() {
        var registerWrap = this.element;
        registerWrap.querySelector('.register-start').classList.remove('d-none');
        registerWrap.querySelector('.register-init').classList.add('d-none');
        registerWrap.querySelector('.register-complete').classList.add('d-none');
        registerWrap.querySelector('.register-complete').dataset.rToken = null;
        registerWrap.querySelector('.register-complete').dataset.pwdToken = null; 
        
        registerWrap.querySelector('.alert.msg').classList.add('d-none');
        registerWrap.querySelector('.alert.msg').innerHTML = 'Поля, обозначенные звездочкой (<span class="text-danger">*</span>), обязательны для заполнения';
        
        var capchaStart = helper.renderCapcha(registerWrap.querySelector('.d-capcha-start'));

        setTimeout(() => {
            window.smartCaptcha.reset(capchaStart.dataset.id)
        }, 100);
    }

    btnStart() {
        var captchaId = this.element.querySelector('#smart-captcha')?.dataset?.id;
        var valid, invalid = false;
        var registerWrap = this.element;
        
        valid = validator.checkPhone(
            registerWrap.querySelector('#phone'), 
            registerWrap.querySelector(`.valid-phone`)
        );

        if (valid) {
            invalid = valid
        }

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

        if (validator.checkAccept(registerWrap.querySelector('#accept'),registerWrap.querySelector('.valid-accept'))) {
            invalid = true;
        }

        if (validator.checkAccept(registerWrap.querySelector('#acceptPerson'),registerWrap.querySelector('.valid-acceptPerson'))) {
            invalid = true;
        }

        if (invalid) {
            return false;
        }

        window.webSDK.recoveryInit({
            'login': registerWrap.querySelector('#phone').value.replace(/[^\w\s!?]/g,''),
            'captcha': window.smartCaptcha.getResponse(captchaId)
        }).then(function (resolve) {
            registerWrap.querySelector('.register-start').classList.add('d-none');
            registerWrap.querySelector('.register-complete').classList.remove('d-none');
            registerWrap.querySelector('.register-complete').dataset.pwdToken = resolve.data.pwdToken;

            if (resolve.data.message.indexOf('почтовый ящик') != '-1') {
                registerWrap.querySelector('.emailCode').classList.remove('d-none');
                registerWrap.querySelector('.alertEmailView').innerHTML = resolve.data.message;
                registerWrap.querySelector('.register-complete').dataset.type = 'email';
            } else {
                registerWrap.querySelector('.smsCode').classList.remove('d-none');
                registerWrap.querySelector('.alertSmsCode').innerHTML = resolve.data.message;
                registerWrap.querySelector('.register-complete').dataset.type = 'sms';
            }

        }).catch(function (e) {
            if (e.data?.errors?.captcha) {
                registerWrap.querySelector('.valid-captcha').innerText = e.data?.errors?.captcha?.[0];
                window.smartCaptcha.reset(captchaId);
            }

            if (e.data?.message?.includes("не найден в базе данных")) {
                registerWrap.querySelector('.register-start').classList.add('d-none');
                registerWrap.querySelector('.register-init').classList.remove('d-none');
                helper.renderCapcha(registerWrap.querySelector('.d-capcha-init'));
            }
        });
    }

    btnReg() {
        var captchaId = this.element.querySelector('#smart-captcha')?.dataset?.id;
        var valid, invalid = false;
        var registerWrap = this.element;
        
        registerWrap.querySelectorAll('.alert.alert-danger.alert-dismissible').forEach(function(e) {
            e.remove();
        });

        var options = {
            firstName: registerWrap.querySelector('#firstName').value,
            lastName: registerWrap.querySelector('#lastName').value,
            middleName: registerWrap.querySelector('#middleName').value                    
        };
        
        for (var key of Object.keys(options)) {
            valid = validator.checkTextRu(
                registerWrap.querySelector(`#${key}`), 
                registerWrap.querySelector(`.valid-${key}`)
            );

            if (valid) {
                invalid = valid
            }
        }

        options.email = registerWrap.querySelector('#email').value;

        valid = validator.checkEmail(
            registerWrap.querySelector('#email'), 
            registerWrap.querySelector(`.valid-email`)
        );

        if (valid) {
            invalid = valid
        }

        options.phone = registerWrap.querySelector('#phone').value;     

        valid = validator.checkPhone(
            registerWrap.querySelector('#phone'), 
            registerWrap.querySelector(`.valid-phone`)
        );

        if (valid) {
            invalid = valid
        }

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

        var validGender = false;

        registerWrap.querySelectorAll('.gender').forEach(function (el) {
            if (el.checked) {
                registerWrap.querySelector('.valid-gender').innerHTML = '';
                validGender = true;
                options.gender = el.value;
            }
        });

        if (!validGender) {
            registerWrap.querySelector('.valid-gender').innerHTML = '<span class="text-danger">укажите Ваш пол</span>';
            invalid = true;
        }

        registerWrap.querySelectorAll('.msg-valid').forEach(function (el) {
            el.innerHTML = '';
        });

        window.webSDK.registerInit({
            firstName: options.firstName,
            lastName:  options.lastName,
            middleName: options.middleName,
            birthDate: registerWrap.querySelector('#birthDate').value,
            email: options.email,
            phone: options.phone,
            gender: options.gender,
            captcha: window.smartCaptcha.getResponse(captchaId)
        }).then(function(resolve) {
            registerWrap.querySelector('.register-init').classList.add('d-none');
            registerWrap.querySelector('.register-complete').classList.remove('d-none');
            registerWrap.querySelector('.register-complete').dataset.rToken = resolve.data.rToken;
            
            if (resolve.data && resolve.data.email == 'true') {
                registerWrap.querySelector('.emailCode').classList.remove('d-none');
                registerWrap.querySelector('.emailView').innerHTML = options.email;
            } else {
                registerWrap.querySelector('.smsCode').classList.remove('d-none');
                registerWrap.querySelector('.smsView').innerHTML = options.phone;
            }
            
        }).catch(function(error) {
            window.smartCaptcha.reset(captchaId);
            helper.sendRequest({
                data: {'error': error, method: 'registerInit'}
            }, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");

            var registerAlert = document.getElementById('register-alert');

            if (! registerAlert) {
                var registerAlert = document.createElement('div');
                registerAlert.classList = 'alert alert-danger alert-dismissible fade';
                registerAlert.setAttribute('role', 'alert');

                var divMsg = document.createElement('div');
                divMsg.classList = 'alert-msg';
                registerAlert.append(divMsg);

                var buttonClose = document.createElement('button');
                buttonClose.classList = 'close';
                buttonClose.dataset.dismiss ='alert';
                buttonClose.setAttribute('aria-label', 'Close');
                buttonClose.innerHTML = '<span aria-hidden="true">&times;</span>';
                registerAlert.append(buttonClose);
                registerWrap.prepend(registerAlert);
            }

            if (error.data.message) {
                registerAlert.classList = 'alert alert-danger alert-dismissible fade show';
                registerAlert.querySelector('.alert-msg').innerHTML = error.data.message;
            } else {
                for (var prop in error.data) {
                    if (error.data[prop]) {
                        var el = registerWrap.querySelector('.valid-' + prop)
                        el.innerHTML = error.data[prop];
                    }
                }
            }
        });
    }

    btnComplite() {
        var registerWrap = this.element;
        
        if (registerWrap.querySelector('.register-complete').dataset.pwdToken !== "null") {
            var type = registerWrap.querySelector('.register-complete').dataset.type; 
            var code = registerWrap.querySelector('#emailCode'); 
            
            if (type == 'sms') {
                var code = registerWrap.querySelector('#smsCode');
            }

            this.recoveryComplite(code, type);
        } else {
            this.registerComplete();
        }
    }

    registerComplete() {
        var registerWrap = this.element;

        window.webSDK.registerComplete({
            rToken: registerWrap.querySelector('.register-complete').dataset.rToken,
            emailCode: registerWrap.querySelector('#emailCode').value,
            smsCode: registerWrap.querySelector('#smsCode').value,
            password: registerWrap.querySelector('#password').value
        }).then(function(response) {
            registerWrap.querySelector('.alert.filter').classList.add('d-none');
            
            var successAlert = document.createElement('div');
            successAlert.classList = 'alert alert-success alert-dismissible fade show';
            successAlert.setAttribute('role', 'alert');

            var divMsg = document.createElement('div');
            divMsg.classList = 'alert-msg';
            divMsg.innerHTML = '<p>Регистрация завершена.</p>'
            + '<p>' + response.data.text + '</p>';
            successAlert.append(divMsg);

            var buttonClose = document.createElement('button');
            buttonClose.classList = 'close';
            buttonClose.dataset.dismiss ='alert';
            buttonClose.setAttribute('aria-label', 'Close');
            buttonClose.innerHTML = '<span aria-hidden="true">&times;</span>';
            successAlert.append(buttonClose);
            document.getElementById('alert-system').prepend(successAlert);
            registerWrap.querySelector('.register-complete').classList.add('d-none');
        }).catch(function(error) { 
            helper.sendRequest({
                data: {'error': error, method: 'registerComplete'}
            }, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");                                 
            for (var prop in error.data) {
                if (error.data[prop]) {
                    var classValid = prop.split('.')[1];

                    if (classValid) {
                        var el = registerWrap.querySelector('.valid-' + prop.split('.')[1]);
                    } else {
                        var el = registerWrap.querySelector('.valid-' + prop);
                    }
                    
                    el.innerHTML = error.data[prop];
                }
            }
            
            $('html, body').animate({scrollTop:0}, '300');
        });
    }

    recoveryComplite(inputCode, type) {
        var registerWrap = this.element;
        var valid, invalid = false;

        valid = validator.checkNotEmpty(
            inputCode, 
            registerWrap.querySelector('.valid-' + type + 'Code')
        );
        
        if (valid) {
            invalid = valid
        }

        valid = validator.checkNotEmpty(
            registerWrap.querySelector('#password'), 
            registerWrap.querySelector('.valid-password')
        );
        
        if (valid) {
            invalid = valid
        }

        if (invalid) {
            return false;
        }

        window.webSDK.recoveryComplete({
            'pwdToken': registerWrap.querySelector('.register-complete').dataset.pwdToken,
            'password': registerWrap.querySelector('#password').value,
            'code': inputCode.value
        }).then(function (result) {
            registerWrap.querySelector('.alert.msg').classList.add('d-none');
            
            var successAlert = document.createElement('div');
            successAlert.classList = 'alert alert-success alert-dismissible fade show';
            successAlert.setAttribute('role', 'alert');

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

            var buttonClose = document.createElement('button');
            buttonClose.classList = 'close';
            buttonClose.dataset.dismiss ='alert';
            buttonClose.setAttribute('aria-label', 'Close');
            buttonClose.innerHTML = '<span aria-hidden="true">&times;</span>';
            successAlert.append(buttonClose);
            document.getElementById('alert-system').prepend(successAlert);
            registerWrap.querySelector('.register-complete').classList.add('d-none');

            $.ajax({
                method: "POST",
                crossDomain: false,
                url: "/forget",
                contentType: "application/x-www-form-urlencoded",
                dataType: "json",
                data: {
                    token: popupBody.dataset.csrf,
                    uid: forget.data.uid,
                    password: forgetPasswd
                }
            });
        }).catch(function (e) {
            helper.sendRequest({
                data: {'error': e, method: 'recoveryComplete'}
            }, helper.getHostname() + '/api/log', "POST", "json", true, "application/json");
            
            var msg = registerWrap.querySelector('.msg');
                msg.classList.add('alert-danger');
                msg.classList.remove('filter');

            if (e.data && e.data.error) {
                msg.innerHTML = e.data.error
            }
        });
    }
}