const axios = require('axios');
const memoize = require("memoizee");
import { TempValue } from './types';
import { randomSleep } from './utils';

require('dotenv').config();

const apiURL:string|null = process.env.ROOM_API_CALL || null;

if (apiURL === null) {
    console.log("Missing value for ROOM_API_CALL in .env file");
    process.exit();
}

var loadApi = async function() {
    try {

        let retries:number = 3;
        let temperature:TempValue = null;

        while (retries > 0) {

            retries--;
            const res = await axios.get(apiURL,{
                headers: { "Accept-Encoding": "gzip,deflate,compress" } 
            });

            if (res.status == 200) {
                temperature = res.data.temperature;
                retries = 0;
            } else {
                console.log("API GET ERROR CODE: ", res.status);
                await randomSleep(1500, 8000);
            }
        }

        return temperature;

    } catch (err:any) {
        console.log(apiURL + " => " + err.message);
    }

    return null;
};

const memoized = memoize(loadApi, { maxAge: 10000 }); // 10 seconds cache

export class Room
{
    public async getTemperature() : Promise<TempValue> 
    {
        return memoized();        
    }
}