
const STORAGE_KEYS = {
    profile: 'profile',
    gobizUser: 'gobiz_user',
};

const API_ROOT = 'http://tongkho.depyte.com/api/';

const ENDPOINTS = {
    login: '/Customers/login',
    me: '/Customers/me',
};

const POUP_DOM = {
    container: '#popupContainer',
    login: '.login',
    profile: '.profile',
    closeButton: '#closeButton',
    usernameInput: '#usernameInput',
    passwordInput: '#passwordInput',
    errorMessage: '#popupMessage',
    fullName: '#fullName',
    username: '#username',
    avatar: '#profileImage',
    loginButton: '#loginButton',
    logoutButton: '#logoutButton',
    loginButtonText: '.loginButtonText',
    loginLoader: '#loginLoader'
};

HTML_FORM = {
    login: 'login.html',
    profile: 'logout.html'
};

ERROR_MESSAGE = {
    emtyUsername: "Bạn chưa nhập tài khoản",
    emtyPass: "Bạn chưa nhập mật khẩu",
    loginFail: "Đăng nhập không thành công.<br/>Vui lòng thử lại!",
    exception: "Có lỗi xảy ra, vui lòng thử lại!",
};

$(document).ready(function () {
    main();
});

/**
 * hàm đóng popup
 * @param element
 */
function onClose(element) {
    window.close();
}

let isLoggedIn = false;
let isInited = false

/**
 * Main function of popup
 */
function main() {

    $(document).keyup(function(e) {
        if(e.which == 13) {
            $("#btn-start").trigger('click');
        }
    });



    // bắt enter
    $(document).keyup(function(e) {
        if(e.which == 13 && isLoggedIn == false) {
            $(POUP_DOM.loginButton).trigger('click');
        }
    });

    initDOM();

    chrome.storage.local.get(STORAGE_KEYS.gobizUser, function (result) {
        console.log("du lieu doc duoc la", result);
        if (result.hasOwnProperty(STORAGE_KEYS.gobizUser) && result[STORAGE_KEYS.gobizUser] && result[STORAGE_KEYS.gobizUser].id) {
            isLoggedIn = true;

            // neu da login thi load prifile
            loadProfilePage();
        } else {
            isLoggedIn = false;

            // neu chua login thi load form login
            loadLoginPage();
        }

    });
}

function initDOM() {
    $(POUP_DOM.closeButton).click(onClose);
    $(POUP_DOM.loginButton).click(login);
    $(POUP_DOM.usernameInput).keyup(function () {
        showLoginMessage("");
    });

    $(POUP_DOM.passwordInput).keyup(function () {
        showLoginMessage("");
    });

    $(POUP_DOM.logoutButton).click(logout);

}


/**
 * load form login va gan cac listener
 */
function loadLoginPage() {

    $(POUP_DOM.profile).css("display", "none");
    $(POUP_DOM.login).css("display", "block");
    $(POUP_DOM.usernameInput).val('');
    $(POUP_DOM.passwordInput).val('');

    resizePopup();

}

/**
 * load trang profile
 */
function loadProfilePage() {

    $(POUP_DOM.profile).css("display", "flex");
    $(POUP_DOM.login).css("display", "none");

    chrome.storage.local.get(STORAGE_KEYS.profile, function (result) {
        if (result.hasOwnProperty(STORAGE_KEYS.profile)) {
            let profile = result.profile;
            $(POUP_DOM.fullName).html(profile.fullName);
            $(POUP_DOM.username).html("TK: " + (profile.username ? profile.username : ""));

            if (typeof profile.avatar == 'string' && profile.avatar !== "")
                $(POUP_DOM.avatar).attr("src", profile.avatar);

            resizePopup();
        }
    });

}

/**
 * ham handle login
 */
function login() {
    const username = $(POUP_DOM.usernameInput).val();
    const pass = $(POUP_DOM.passwordInput).val();

    if (username == "") {
        showLoginMessage(ERROR_MESSAGE.emtyUsername);
        return;
    }

    if (pass == "") {
        showLoginMessage(ERROR_MESSAGE.emtyPass);
        return;
    }

    showLoading(true);

    // The data we are going to send in our request
    let data = {
        password: pass,
    };

    if (username.indexOf("@") != -1) {
        data.email = username;
    } else {
        data.username = username;
    }

    // The parameters we are gonna pass to the fetch function
    let fetchData = {
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': ''
        }
    };

    fetch(API_ROOT + ENDPOINTS.login, fetchData)
        .then((response) => {
            return response.json();
        })
        .then((jsonObject) => {
            // tat loading
            showLoading(false);

            console.log("data", jsonObject);
            if (jsonObject.hasOwnProperty("id")) {
                handleLoginSuccess(jsonObject);
            } else {
                showLoginMessage(ERROR_MESSAGE.loginFail);
            }
        }).catch(function (error) {
            // tat loading
            showLoading(false);
            showLoginMessage(ERROR_MESSAGE.exception);
        });
}

function showLoading(isShow) {
    if (isShow) {
        $(POUP_DOM.loginButtonText).css("display", "none");
        $(POUP_DOM.loginLoader).css("display", "flex");
    } else {
        $(POUP_DOM.loginButtonText).css("display", "flex");
        $(POUP_DOM.loginLoader).css("display", "none");
    }
}

/**
 * ham xu ly login successs
 * @param session
 */
function handleLoginSuccess(session) {

    // luu du lieu
    chrome.storage.local.set({
        [STORAGE_KEYS.gobizUser]: session
    }, function () {
        console.log("da luu thanh cong");
    });

    // fetch du lieu nguoi dung
    fetch(API_ROOT + ENDPOINTS.me + "?access_token=" + session.id)
        .then((response) => {
            return response.json();
        })
        .then((jsonObject) => {
            console.log("fetch user", jsonObject);
            if (jsonObject.hasOwnProperty('error')) {
                showLoginMessage(jsonObject.error.message);
            } else {
                saveAndFillInfoToProfile(jsonObject);
            }
        }).catch(function (error) {
            showLoginMessage("Có lỗi xảy ra, vui lòng thử lại!");
        });
}

/**
 * luu va dien du lieu sau khi goi api me
 * @param info
 */
function saveAndFillInfoToProfile(info) {
    // luu du lieu
    chrome.storage.local.set({
            [STORAGE_KEYS.profile]: info
        }
        , function () {
            console.log("da luu thanh cong");
            loadProfilePage();
        });
}


/**
 * ham handle logout
 */
function logout() {
    isLoggedIn = false;
    // xoa het du lieu
    chrome.storage.local.clear();

    loadLoginPage();
}

/**
 * ẩn hiện thông báo lỗi
 * @param message
 */
function showLoginMessage(message) {
    let haveError = (typeof message == 'string' && message !== "");
    $(POUP_DOM.errorMessage).css("display", haveError ? "flex" : "none");
    $(POUP_DOM.errorMessage).html(message);

    resizePopup();
}

/**
 * ham resize lai popup
 */
function resizePopup() {
    let height = $(POUP_DOM.container).height();
    let random = Math.round(Math.random());
    $('body').css("height", height + random);
    $('html').css("height", height + random);
}