/**
    * @file auth.js
    * @brief Скрипт авторизации, содержит функции и переменные для входа, регистрации и управления блоком авторизации
*/

addEventListener("load", function() {
movementMenu("authorizationDiv");

let authorizationButtonId = document.getElementById("authorizationButton");
const authorizationDivId = document.getElementById("authorizationDiv");

if (getCookie('Login') == "true") {
    authorizationButtonId.style.background = "url(../../img/pict/mc_iconslyb.svg) -1038px 1px";
    document.documentElement.style.setProperty('--autButBackX', '-1038');
    document.documentElement.style.setProperty('--autButBackY', '1');
    authorizationButtonId.onclick = function() {
        jsonrpcRequest("logoutUser", { logoff: "Выйти" })
        .then(response => {
            location.reload();
        })     
    };
} else if (getCookie('Login') == "false") {
    authorizationButtonId.style.background = "url(../../img/pict/mc_iconslyb.svg) -756px 1px";
    document.documentElement.style.setProperty('--autButBackX', '-756');
    document.documentElement.style.setProperty('--autButBackY', '1');
    authorizationButtonId.onclick = function() {
        const el = authorizationDivId;
        if (el.style.visibility === "visible") {
            el.style.visibility = "hidden";
        } else {
            el.style.visibility = "visible";
            el.style.top = "20%";
            el.style.left = "50%";
            el.style.transform = "translate(-50%, -20%)";
        }
    };         
}

});

/**
    * @brief Закрывает блок авторизации
*/
function authorizationDivCloseFun() {
    document.getElementById("authorizationDiv").style.visibility = "hidden";
}

/**
    * @brief Создаёт форму кнопки входа
*/
function loginButtonFunCreate() {
    document.querySelector(".authorizationDivMainDiv").innerHTML = `
        <div id="BackArrow" onClick="mainButtonFunCreate()"></div>
        <div class="formRow">
            <label>{{login_label}}:</label>
            <input type="text" id="loginInput" name="login">
        </div>
        <div class="formRow">
            <label>{{password_label}}:</label>
            <input type="password" id="passInput" name="pass" autocomplete="">
        </div>
        <div class="formRow">
            <button type="button" id="loginButton" onClick="loginButtonFun()">{{login}}</button>
        </div>
    `;

    const inputLogin = document.getElementById('loginInput');
    const inputPass = document.getElementById('passInput');
    const loginBtn = document.getElementById('loginButton');
    [inputLogin, inputPass].forEach(input => {
        input.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                if (loginBtn.getAttribute('onClick') === 'loginButtonFun()') {
                    loginBtn.click();
                }
            }
        });
    });
}
/**
    * @brief Обрабатывает нажатие кнопки входа
*/
function loginButtonFun() {
	var login = document.getElementById("loginInput").value;
	var pass = document.getElementById("passInput").value;
    jsonrpcRequest("loginUser", { login: login, pass: pass, log: "Войти" })
    .then(response => {
        if (response == "true") {
            location.reload();
        } else {
            messageFunction("{{incorrect_login_password}}");
        }
    });
}

/**
    * @brief Создаёт форму кнопки регистрации
*/
function registrationButtonFunCreate() {
    document.querySelector(".authorizationDivMainDiv").innerHTML = `
        <div id="BackArrow" onClick="mainButtonFunCreate()"></div>
        <div class="formRow">
            <label>{{login_label}}:</label>
            <input type="text" id="loginInput" name="login">
        </div>
        <div class="formRow">
            <label>{{password_label}}:</label>
            <input type="text" id="passInput" name="pass">
        </div>
        <div class="formRow">
            <label>{{repeat_password_label}}:</label>
            <input type="text" id="passСheckInput" name="pass">
        </div>
        <div class="formRow">
            <label>{{email_label}}:</label>
            <input id="emailInput">
        </div>
        <div class="formRow">
            <button type="button" id="loginButton" onClick="registrationButtonFun()">{{register}}</button>
        </div>
    `;
}
/**
    * @brief Обрабатывает нажатие кнопки регистрации
*/
function registrationButtonFun() {
	var login = document.getElementById("loginInput").value;
	var pass = document.getElementById("passInput").value;
	var passСheck = document.getElementById("passСheckInput").value;
	var email = document.getElementById("emailInput").value;
    if (login.trim() == "" || pass.trim() == ""  || passСheck.trim() == ""  || email.trim() == "" ) {
        messageFunction("{{fill_all_fields}}");
        return;
    }
    if (pass != passСheck) {
        messageFunction("{{passwords_do_not_match}}");
        return;
    }
    jsonrpcRequest("registerUser", { login: login, pass: pass, email: email }).then(response => {
        if (response == "true") {
            messageFunction("{{account_creation_request_sent}}");
        } else if (response == "name_exists") {
            messageFunction("{{user_exists}}");
        } else {
            messageFunction("{{account_creation_request_error}}");
        }
    });
}

/**
    * @brief Создаёт главную форму выбора между входом и регистрацией
*/
function mainButtonFunCreate() {
    document.querySelector(".authorizationDivMainDiv").innerHTML = `
        <div class="formRow">{{account_authorization}}</div>
        <div class="formRow">
            <button type="button" id="loginButton" onClick="loginButtonFunCreate()">{{login}}</button>
            <button type="button" id="loginButton" onClick="registrationButtonFunCreate()">{{register}}</button>
        </div>
    `;
}
