const btnLogin = document.querySelector('#btn_login');
const inputPassword = document.querySelector('#login #password');
const btnLoginPage = document.querySelector('.btn-login');
const btnUserProfile = document.querySelector('.btn-userProfile');
const btnLogout = document.querySelector('.btn-logout');
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');
})

inputPassword.addEventListener('keyup', loginByEnter);
btnLogin.addEventListener('click', login);

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

function login(){
    console.log('login!');
    var url = "https://www.choozmo.com:8887/login";
    var username = $('#username').val();
    var password = $('#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;
    }

    
    var data = "grant_type=&username=" + username + "&password="+password+"&scope=&client_id=&client_secret=";
    const headers = {
        "accept": "application/json",
        "Content-Type": "application/x-www-form-urlencoded"
    }
    $('.loading').show();
    console.log(data);
    axios({
        method: 'post',
        url: url,
        headers: headers,
        data: data
    }).then(res => {
        console.log(res.data);
        document.cookie = 'jwt_token='+res.data.access_token;
        if(res.data.access_token!=null && res.data.veri == 'ok') {
            var title = "登入成功";
            if (lang == 'en') { // 英文版訊息
                title = "Login Successfully!"
            }

            Swal.fire({
                title: title,
                icon: 'success',
                confirmButtonColor: '#3085d6',
            });
            $('.loading').hide();
            window.setTimeout(() => {
                window.location.href = 'user_profile2.html';
            }, 2000);
            btnLoginPage.style.display = 'none';
            
        } else if (res.data.access_token!=null && res.data.veri != 'ok') {
            var title = "請前往信箱完成驗證";
            $('.loading').hide();
            if (lang == 'en') { // 英文版訊息
                title = "Please check your email box to get validated!"
            }

            Swal.fire({
                title: title,
                icon: 'error',
                text: responseOBJ.detail,
                confirmButtonColor: '#3085d6',
            });
        } else {
            var title = "登入失敗";
            $('.loading').hide();
            if (lang == 'en') { // 英文版訊息
                title = "Login Failed!"
            }
            Swal.fire({
                title: title,
                icon: 'error',
                text: responseOBJ.detail,
                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',
        });
        $('.loading').hide();
    })
}
/*     var xhr = new XMLHttpRequest();
    xhr.open("POST", url);
    xhr.setRequestHeader("accept", "application/json");
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            console.log(xhr.responseText); // test
            responseOBJ = JSON.parse(xhr.responseText);
            // document.cookie = 'jwt_token='+responseOBJ.jwt_token    // access_token -> jwt_token
            document.cookie = 'jwt_token='+responseOBJ.access_token;
            console.log(responseOBJ);
            if (responseOBJ.access_token!=null)
                {
                    var title = "登入成功";

                    if (lang == 'en') { // 英文版訊息
                        title = "Login Successfully!"
                    }

                    Swal.fire({
                        title: title,
                        icon: 'success',
                        confirmButtonColor: '#3085d6',
                    });
                    window.setTimeout(() => {
                        window.location.href = 'user_profile2.html';
                    }, 2000);
                    btnLoginPage.style.display = 'none';
                }
            else{
                var title = "登入失敗";

                if (lang == 'en') { // 英文版訊息
                    title = "Login Failed!"
                }

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

    // 登入資料檢查
    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;
    }

    
    result = xhr.send(data);
    console.log(result);
} */

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