
const login_messages = document.getElementById('login-messages-inpt');
const otp_messages = document.getElementById('otp-messages-inpt');
const forgot_messages = document.getElementById('forgot-messages');

const target_url = () => {
    const url_params = new URL(window.location.toLocaleString()).searchParams;
    const target_url = url_params.get('o');
    return target_url ? target_url : '/';
};
const sign_up = () => {
    if (SIGNIN_URL) {
        location.href=SIGNUP_URL;
    }
};
const on_forgot_passwd = () => {
    if (RESET_URL) {
        if (forgot_messages) {
            forgot_messages.classList.remove('hidden');
            forgot_messages.innerHTML='<p>For <u>password reset</u> you need:</p><p> a <b>valid user, email</b> and a <b>verified TOTP</b> code.</p><p>Otherwise contact with Service Administrators.</p>' 
        }
        const main_form = document.getElementById('main-form');
        const otp_form = document.getElementById('otp-form');
        const btn_otp_forgot_passwd = document.getElementById('otp-forgot-password');
        const otp_login_link = document.getElementById('otp-login-link')
        const btn_otp_signin = document.getElementById('otp-signin-button');
        const name = document.getElementById('login-name-inpt').value;
        if (name == '') {
            login_messages.innerHTML='Enter a name';
            return;
        }
        main_form.classList.add('hidden');
        if (btn_otp_forgot_passwd) { btn_otp_forgot_passwd.classList.remove('hidden') };
        if (otp_login_link) { otp_login_link.classList.remove('hidden') };
        if (btn_otp_signin) { btn_otp_signin.classList.add('hidden') };
        otp_form.classList.remove('hidden');
    }
};
const forgot_passwd = async() => {
    const otp_loading = document.getElementById('otp-loading');
    const otp_btns = document.getElementById('otp-btns');
    const elem_otp_auth = document.getElementById('login-totp-inpt');
    const elem_name = document.getElementById('login-name-inpt');
    const otp_form = document.getElementById('otp-form');
    let name = '';
    if (elem_name) { name = elem_name.value; }
    let otp_auth = '';
    if (elem_otp_auth) {
        otp_auth = elem_otp_auth.value;
        if (otp_auth == '') {
            otp_messages.innerHTML='Please enter a valid TOTP code';
            return;
        }
        const numbers = /^[0-9]+$/;
        if(! otp_auth.match(numbers) || otp_auth.length != totp_digits ) {
            otp_messages.innerHTML='Please enter a valid TOTP code';
            return;
        }
    }
    if (RESET_URL) {
        const input_data = { name, value: otp_auth };
        const response = await fetch(RESET_URL, {
            method: 'POST',
            body: JSON.stringify(input_data),
            headers: {
                'Content-type': 'application/json; charset=UTF-8',
                // 'cookie': document.cookie,
            }
        });
        if (otp_loading) { utils.css('show',otp_loading); }
        if (otp_btns) { utils.css('hide',otp_btns); }
        if (response.ok && response.status === 200 ) {
            if (otp_loading) { utils.css('hide',otp_loading); }
            const data = await response.text();
            if (otp_form) { utils.css('hide',otp_form); }
            if (forgot_messages) { forgot_messages.innerHTML=data }
            setTimeout(() => { location.href = target_url() }, settings.toast_copy_timeout);
        } else {
            if (otp_loading) { utils.css('hide',otp_loading); }
            if (otp_btns) { utils.css('show',otp_btns); }
            if (forgot_messages) { forgot_messages.innerHTML='Errors in password reset'; }
            return false;
        }
    }
};
const set_name = (elem) => {
    if (login_messages.innerHTML!='') { login_messages.innerHTML=''; }
    if (forgot_messages) { forgot_messages.classList.add('hidden'); }
};
const set_password = (elem) => { 
    if (login_messages.innerHTML!='') { login_messages.innerHTML=''; }
    if (forgot_messages) { forgot_messages.classList.add('hidden'); }
};
const log_in = async () => { 
    const main_form = document.getElementById('main-form');
    const main_btns = document.getElementById('main-btns');
    const main_loading = document.getElementById('main-loading');
    const otp_form = document.getElementById('otp-form');
    const name = document.getElementById('login-name-inpt').value;
    if (name == '') {
        login_messages.innerHTML='Enter a name';
        return;
    }
    const password = document.getElementById('login-password-inpt').value;
    if (password == '') {
        login_messages.innerHTML='Please choose a password';
        return;
    }
    const data = {
        name,
        password,
        //timestamp:  new Date().toLocaleString(),
    };
    if (main_btns) { utils.css('hide',main_btns); }
    if (main_loading) { utils.css('show',main_loading); }
    const response = await fetch(SIGNIN_URL, {
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
            'Content-type': 'application/json; charset=UTF-8',
            // 'cookie': document.cookie,
        }
    });
    if (main_loading) { utils.css('hide',main_loading); }
    if (response.ok && response.status === 200 ) {
        const data = await response.text();
        if (data.includes('true') && otp_form) {
            main_form.classList.add('hidden');
            otp_form.classList.remove('hidden');
        } else {
            location.href=target_url();
        }
    } else {
        login_messages.innerHTML='Signin was not OK';
        if (main_btns) { utils.css('show',main_btns); }
        return false;
    }
};
const set_totp = (elem) => {
    if (otp_messages.innerHTML!='') { otp_messages.innerHTML=''; }
};
const otp_in = async () => { 
    const otp_btns = document.getElementById('otp-btns');
    const otp_loading = document.getElementById('otp-loading');
    const name = document.getElementById('login-name-inpt').value;
    if (name == '') {
        otp_messages.innerHTML='Enter a name';
        return;
    }
    const password = document.getElementById('login-password-inpt').value;
    if (password == '') {
        otp_messages.innerHTML='Please choose a password';
        return;
    }
    const otp_auth = document.getElementById('login-totp-inpt').value;
    if (otp_auth == '') {
        otp_messages.innerHTML='Please enter a valid TOTP code';
        return;
    }
    const numbers = /^[0-9]+$/;
    if(! otp_auth.match(numbers) || otp_auth.length != totp_digits ) {
        otp_messages.innerHTML='Please enter a valid TOTP code';
        return;
    }
    const data = {
        name,
        password,
        otp_auth,
    };
    if (otp_btns) { utils.css('hide',otp_btns);}
    if (otp_loading) { utils.css('show',otp_loading); }
    const response = await fetch(SIGNIN_URL, {
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
            'Content-type': 'application/json; charset=UTF-8',
            // 'cookie': document.cookie,
        }
    });
    if (otp_loading) { utils.css('hide',otp_loading); }
    if (response.ok && response.status === 200 ) {
        location.href=target_url();
    } else {
        if (otp_btns) { utils.css('show',otp_btns);}
        otp_messages.innerHTML='Signin was not OK';
        return false;
    }
};
const on_openid = (item) => {
    location.href=`/openid/${item}`;
};
const restart = () => { 
    const main_form = document.getElementById('main-form');
    const main_btns = document.getElementById('main-btns');
    const otp_form = document.getElementById('otp-form');
    const otp_btns = document.getElementById('otp-btns');
    if (otp_btns) { utils.css('show',otp_btns);}
    if (main_btns) { utils.css('show',main_btns);}
    otp_form.classList.add('hidden');
    forgot_messages.classList.add('hidden');
    forgot_messages.innerHTML='';
    main_form.classList.remove('hidden');
    login_messages.innerHTML='';
    otp_messages.innerHTML='';
};
window.addEventListener('load', () => {
    const show_password = document.getElementById('show-password');
    const input_password = document.getElementById('login-password-inpt')
    const otp_logo_link = document.getElementById('otp-logo-link')
    if (show_password) {
        show_password.addEventListener('click', (ev) => {
            ev.preventDefault();
            [...show_password.children].forEach(it => {
               it.classList.toggle('hidden');
            });
            if (input_password.type == 'password') {
                input_password.type = 'text';
            } else  {
                input_password.type = 'password';
            }
        });
    }
    if (otp_logo_link) { otp_logo_link.href = location.href; }
});