import localforage from 'localforage'
import axios from 'axios'

const urlCF = 'https://us-central1-vixoniccloudcom.cloudfunctions.net/rexTokenCentralizer'
const tokenCF = 'd2dca806-4f70-41a3-ab70-0fe9bf051d2e'
let updateTimer: any

function setUpdateTime(milliseconds: any, requestData: any) {
    clearTimeout(updateTimer)
    if (milliseconds === null) return
    updateTimer = setTimeout(requestData, milliseconds)
}

function getToken(apiDomain: any) {
    try {
        const config = { 'Authorization': tokenCF }
        const response = axios({
            method: 'post',
            url: urlCF,
            headers: config,
            data: {
                orgDomain: apiDomain // This is the body part
            }
        })
        return response
    } catch (error) {
        console.error(error);
        return error
    }
}

function setTokenLocal(token: any, apiDomain: any) {
    localforage.config({ name: `request_${apiDomain}` })
    localforage.setItem('rexmas', {
        token: token,
        apiDomain: apiDomain,
        date: Date.now()
    }, (err) => { if (err) console.log(err) })
}




export default function setToken(apiDomain: any, requestData: any) {
    let pt: any = getToken(apiDomain)
    pt.then(function (response: any) {
        console.log('rr...', response)
        let token = response.data.token
        if (token === '') {
            console.log(response.data.msg)
            // renderLog(response.data.msg)
            setUpdateTime(null, requestData)
        } else {
            console.log('Access granted to Rex+ API')
            setTokenLocal(token, apiDomain)
            setUpdateTime(2000, requestData)
        }
        return
    })
        .catch(function (error: any) {
            console.log(error);
            console.log(`Error getting token ${error.response.data && error.response.data.detalle}`)
            //   setUpdateTime(null)
            return
        })
}



