
const invite_sec_form= document.getElementById('invite-sec-form');
const invite_restart= document.getElementById('invite-restart');
const invite_messages_inpt = document.getElementById('invite-messages-inpt');
const invite_messages_out = document.getElementById('invite-messages-out');
const expire_value = document.getElementById('expire-value');
const expire_range = document.getElementById('expire-range');
const expire_input = document.getElementById('expire-input');
expire_value.innerHTML = expire_range.value;

const clear_messages = () => {
    if (invite_messages_inpt.innerHTML!='') { invite_messages_inpt.innerHTML=''; }
    if (invite_messages_out.innerHTML!='') { invite_messages_out.innerHTML=''; }
};
const set_email = (elem) => {
    clear_messages();
};
const set_expire_input = (elem) => {
    expire_value.innerHTML = `${expire_input.value} minutes`
    expire_range.value = expire_input.value;
    clear_messages();
};
const set_expire = (elem) => {
    expire_value.innerHTML = `${expire_range.value} minutes`;
    expire_input.value = expire_range.value;
    clear_messages();
};
const show_form = (elem) => {
    invite_restart.classList.toggle('hidden');
    invite_sec_form.classList.toggle('hidden');
};
const invite = async () => { 
    const email = document.getElementById('email-input').value;
    if (email == '') {
        invite_messages_inpt.innerHTML='Enter email ';
        return;
    }
    if (!email.includes('@')) {
        invite_messages_inpt.innerHTML='Please include a valid email';
        return;
    }
    const elem_roles = document.getElementById('roles-select');
    const roles = [...elem_roles.selectedOptions].map(option => option.value).join(',')
    if (roles == '') {
        invite_messages_inpt.innerHTML='Please include a role';
        return;
    }
    let expire = parseInt(expire_input.value) || 0;
    if (expire == 0 ) {
        invite_messages_inpt.innerHTML='Please set expiration valid value';
        return;
    }
    expire = (expire * 60);
    let send_email = document.getElementById('send-email') ?
        document.getElementById('send-email').checked : false;
    const data = {
        email,
        roles,
        expire,
        send_email,
    };
    if (target_url != '') {
        const response = await fetch(target_url, {
            method: 'POST',
            body: JSON.stringify(data),
            headers: {
                'Content-type': 'application/json; charset=UTF-8',
                // 'cookie': document.cookie,
            }
        });
        if (response.ok && response.status === 200 ) {
            clear_messages();
            invite_sec_form.classList.toggle('hidden');
            invite_messages_out.innerHTML=await response.text();
            invite_restart.classList.toggle('hidden');
        } else {
            clear_messages();
            invite_messages_inpt.innerHTML=await response.text();
        }
    }
};