const btnRegister = document.querySelector('.btn-register');
const btnLoginPage = document.querySelector('.btn-login');
const btnUserProfile = document.querySelector('.btn-userProfile');
const btnLogout = document.querySelector('.btn-logout');
const registerPassword = document.querySelector('#register #password');
const btnLoginPage_d = document.querySelector('.login-top .btn-login');
const btnUserProfile_d = document.querySelector('.login-top .btn-userProfile');
const btnLogout_d= document.querySelector('.login-top .btn-logout');
$('.psd_visible').hide();

$('.psd_invisible').click(function(){
    $(this).prev().toggle();
    $(this).toggle();
    $(this).parent().children(':first').attr('type', 'text');
})

$('.psd_visible').click(function(){
    $(this).toggle();
    $(this).next().toggle();
    $(this).parent().children(':first').attr('type', 'password');
})

registerPassword.addEventListener('keyup', registerByEnter);
btnRegister.addEventListener('click', register);

function registerByEnter(e) {
    if (e.keyCode === 13) {
        e.preventDefault();
        console.log('login!');
        register();
    }
};

function validateEmail(email) {
    const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if(re.test(String(email).toLowerCase()) === false) {
        $('#register [name = "email"]').addClass('error');
        if( !$('.error-text').length ) {
            let msg = '請輸入正確E-mail';

            if (lang == 'en') { 
                msg = 'Please enter valid Email format.';
            }

            $('input.error').after('<p class="error-text" set-lan="html:errorEmail">' + msg + '</p>');
        } 
    } else {
        $('#register [name = "email"]').removeClass('error');
        $('.error-text').remove();
    }
    
    return re.test(String(email).toLowerCase());
}

function validatePassword(psd) {
    if(psd.length >=4) {
        $('#register [name = "password"]').removeClass('error');
        $('.error-text').remove();
        return true;
    } else {
        $('#register [name = "password"]').addClass('error');
        if( !$('.error-text').length ) {
            $('input.error').after('<p class="error-text" set-lan="html:errorPsd">密碼至少為4個字元</p>');
        } 
        return false;
    }
}

function validateConfirmPsd(psd1, psd2) {
    if(psd1 == psd2) {
        $('#register #confirm_password').removeClass('error');
        $('.error-text').remove();
        return true;
    } else {
        $('#register #confirm_password').addClass('error');
        if( !$('.error-text').length ) {
            $('input.error').after('<p class="error-text" set-lan="html:errorConsistentPsd">密碼輸入需一致</p>');
        } 
        return false;
    }
}

function getpathId() {
    const urlParams = new URLSearchParams(window.location.search);
    const id = urlParams.get('code');
    return id;
}

console.log(getpathId());

function register() {
    let url = 'https://www.choozmo.com:8887/register';
    let userName = $('#register [name = "username"]').val();
    let email = $('#register [name = "email"]').val();
    let password = $('#register [name = "password"]').val();
    let confirm_psd = $('#register #confirm_password').val();
    let code = getpathId();

    let userObj = {
      username: userName,
      email,
      password
    }

    if(code) {
      url = 'https://www.choozmo.com:8887/register_by_invite';
      userObj = {
        username: userName,
        email,
        password,
        code: code
      }
    }

    // 註冊資料檢查
    if (username == '' || password == '') {
        let title = "註冊失敗";
        let text = "請先輸入您的帳號/密碼";

        if (lang == 'en') { 
            title = "Login Failed!";
            text = "Please enter your username and password";
        }

        Swal.fire({
            title: title,
            icon: 'error',
            text: text,
            confirmButtonColor: '#3085d6',
        });

        return;
    }

    if(userName && validateEmail(email) && validatePassword(password) && validateConfirmPsd(password, confirm_psd)) {
        JsLoadingOverlay.show({
            "overlayBackgroundColor": "#666666",
            "overlayOpacity": 0.6,
            "spinnerIcon": "ball-circus",
            "spinnerColor": "#000",
            "spinnerSize": "3x",
            "overlayIDName": "overlay",
            "spinnerIDName": "spinner",
            "offsetX": 0,
            "offsetY": 0,
            "containerID": null,
            "lockScroll": false,
            "overlayZIndex": 10,
            "spinnerZIndex": 11
        });
        console.log(userObj);
        const headers = {
            "accept": "application/json",
            "Content-Type": "application/json"
        }
        axios({
            method: 'post',
            url: 'https://www.choozmo.com:8887/register',
            headers: headers,
            data: userObj
        }).then(res => {
            console.log(res.data.msg);
            JsLoadingOverlay.hide();
            let text;
            if (lang == 'en') { 
                text = res.data.msg.eng;
            } else {
                text = res.data.msg.zh;
            }
            Swal.fire({
                icon: 'info',
                text: text,
                confirmButtonColor: '#3085d6',
            });
        }).catch(err => {
            console.log(err);
            var title = "錯誤處理中，請稍後再試";

            if (lang == 'en') { // 英文版訊息
                title = "Oops! Errors occurred. Please try it later!"
            }
            Swal.fire({
                title: title,
                icon: 'error',
                confirmButtonColor: '#3085d6',
            });
        })
    }
}


function loginControl() {
    btnLoginPage.style.display = 'block';
    btnLogout.style.display = 'none';
    btnUserProfile.style.display = 'none';
    btnLoginPage_d.style.display = 'block';
    btnLogout_d.style.display = 'none';
    btnUserProfile_d.style.display = 'none';
}

loginControl();
