'use strict';
const axios = require('axios');
const qs = require('qs');
const fs = require('fs');
const { base64encode } = require('nodejs-base64');

function generateToken() {

    var fileData = fs.readFileSync('token.txt', 'utf8');

    var parseData = JSON.parse(fileData);
    var token = parseData.token;
    var expire_time = parseData.expire_time;

    var currentTime = new Date().getTime();
    if (expire_time < currentTime) {
        var client_id = "";
        var client_secret = "";
        var buff = base64encode(client_id + ':' + client_secret);

        var data = { grant_type: 'password', username: '4', password: 'PateL253592' };
        const url = 'https://demo.sevenstarfx.com:6234/oauth2/token';

        const options = {
            method: 'POST',
            headers: { 'Authorization': 'Basic ' + buff, 'Content-Type': 'application/x-www-form-urlencoded' },
            data: qs.stringify(data),
            url,
        };

        axios(options)
            .then((response) => {
                if (response.data != '' && response.data.access_token != '') {
                    var currentTime = new Date().getTime();
                    // add 11 hours in current time for expire time
                    var expireTime = new Date(currentTime + 11 * 60 * 60 * 1000).getTime();
                    var token = response.data.access_token;

                    var jsonData = {};
                    jsonData['token'] = token;
                    jsonData['expire_time'] = expireTime;

                    fs.writeFile('token.txt', JSON.stringify(jsonData), err => {
                        if (err) {
                            console.error(err);
                        } else {
                            console.log('New Token Generated Successfully!');
                        }
                    })
                    return token;
                }
            }, (error) => {
                console.log(error);
            });
    } else {
        return token;
    }
}

module.exports = { generateToken }