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();

$('.loading').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 validateConfirmName() {
    let username = $('#register [name = "username"]').val();
    var regex = new RegExp("^[a-zA-Z0-9 ]+$");
    if(regex.test(username)) {
        $('#register [name = "username"]').removeClass('error');
        $('.error-text').remove();
        return true;
    } else {
        $('#register [name = "username"]').addClass('error');
        if( !$('.error-text').length ) {
            $('input.error').after('<p class="error-text" set-lan="html:errorUsername">請輸入英文字元或數字</p>');
        } 
        return false;
    }
}

function 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();
    var regex = new RegExp("^[a-zA-Z0-9 ]+$");
    // 註冊資料檢查
    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 (!regex.test(userName)) {
        let title = "字元有誤";
        let text = "名稱僅得包含英文及數字";

        if (lang == 'en') { 
            title = "Invalid username!";
            text = "Please enter valid username";
        }

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

        return;
    }

    if(userName && validateConfirmName() && validateEmail(email) && validatePassword(password) && validateConfirmPsd(password, confirm_psd)) {
        $('.loading').show();
        let userObj = {
            username: userName,
            email,
            password
        }
        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);
            $('.loading').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);
            $('.loading').hide();
            var title = "錯誤處理中，請稍後再試";

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


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();
