'use strict'

/**
 * Pages
 */
const MAIN_PAGE = './index.html'

/**
 * Constants
 */
const TIMEOUT_MESSAGE = 3000
const NO_ACCESS_COMPLIANCE = 'Você não tem acesso ao sistema de compliance'
const KEY_PACKAGE_USUARIO = 'br.com.eurides.model.Usuario'

/**
 * Show errors
 * @param {string} text 
 */
function showError(text) {
    const message = document.querySelector('#message')

    message.innerHTML = text
    message.classList.add('alert')
    message.classList.add('alert-danger')

    setTimeout(() => {
        message.innerHTML = ''
        message.classList.remove('alert')
        message.classList.remove('alert-danger')
    }, TIMEOUT_MESSAGE);
}

/**
 * Add listeners from page login
 * @returns void
 */
function addLoginListener() {
    localStorage.clear()
    document.addEventListener('submit', async (event) => {
        event.preventDefault()

        localStorage.clear();

        const userName = document.querySelector('#user').value
        const password = document.querySelector('#password').value
        const hash = CryptoJS.MD5(password).toString().toUpperCase();

        const response = await get(`Login/Default/${userName}/${hash}`)

        if (!response || response.Success === false) {
            showError(response.Message)
            return
        }

        const usuario = response.Data[KEY_PACKAGE_USUARIO][0]
        if (usuario.Compliance !== 'S') {
            showError(NO_ACCESS_COMPLIANCE)
            return
        }

        setSession('user', usuario)

        location.href = MAIN_PAGE
    })
}

document.addEventListener("DOMContentLoaded", () => {
    addLoginListener()
})