'use strict'

/**
 * Base URL
 */
const URL_BASE = 'http://189.42.221.225:11005/api/'

/**
 * Authorization User
 */
const AUTH_USER = 'infotorres'

/**
 * Authorization Password
 */
const AUTH_PASSWORD = '4BA4C3FFC83E9795F23870DBF62C5117'

async function query(method, route, body) {
    const request = {
        method,
        headers: new Headers({
            'Content-Type': 'application/json',
            'Authorization': 'Basic ' + btoa(AUTH_USER + ':' + AUTH_PASSWORD)
        })
    }

    if (body) {
        request['body'] = JSON.stringify(body)
    }

    const response = await fetch(URL_BASE + route, request)

    if (!response.ok) {
        return {
            'Success': false,
            'Message': response.statusText,
            'Timestamp': new Date(),
            'Count': 0,
            'Data': {}
        }
    }

    return await response.json()
}

/**
 * 
 * @param {string} route 
 * @returns Object
 */
async function get(route) {
    return await query('GET', route)
}

/**
 * 
 * @param {string} route 
 * @param {Object} body 
 * @returns Object
 */
async function post(route, body) {
    return await query('POST', route, body)
}

/**
 * Storage user session
 * @param {string} user 
 */
function setSession(key, object) {
    const str = JSON.stringify(object)
    if (str) {
        localStorage.setItem(key, str)
    }
}

/**
 * 
 * @param {string} key 
 * @returns Object
 */
function getSession(key) {
    const str = localStorage.getItem(key)

    if (str) {
        return JSON.parse(str)
    }

    return null
}
