{"size": 1740, "ext": "js", "max_stars_repo_path": "app/apis/wolfram-alpha.js", "max_stars_repo_name": "robcss/mrwolfa", "max_stars_repo_stars_event_min_datetime": "2021-05-04T14:25:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T06:38:16.000Z", "max_issues_repo_path": "app/apis/wolfram-alpha.js", "max_issues_repo_name": "robcss/mrwolfa", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/apis/wolfram-alpha.js", "max_forks_repo_name": "robcss/mrwolfa", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 2, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.064516129, "max_line_length": 117, "alphanum_fraction": 0.5988505747}
require('dotenv').config()

const replies = require("../utils/replies")
const waErrors = require("../utils/waErrors")

const WolframAlphaAPI = require('wolfram-alpha-api');

const waProdId = process.env.NODE_ENV === "development" ? process.env.WOLFRAM_APP_ID_DEV : process.env.WOLFRAM_APP_ID
const waIds = [waProdId, ...process.env.WOLFRAM_APP_ID_BACKUP.split(",")]

const waApis = waIds.map(id => WolframAlphaAPI(id));


const getWolfram = async (question, method) => {

    const waApicall = async (instance) => {
        switch (method) {
            case "spoken":
                return await instance.getSpoken(question);
            case "short":
                return await instance.getShort(question);
        }
    }

    const response = {
        result: null,
        failed: null
    }

    for ([i, waApi] of waApis.entries()) {
        try {
            console.log(`waApi call: ${method} - Attempt with instance: ${i}`)
            response.result = await waApicall(waApi)
            response.failed = false
            return response
        } catch (error) {

            if (error.message !== waErrors.invalidAppId) {
                console.log(error.message)
                response.result = error.message
                response.failed = true
                return response
            }

            console.log(`waApi call: ${method} - Instance ${i} failed - Retrying with instance ${i + 1}`)
        }
    }

    response.result = replies.failed
    response.failed = true
    return response

}


module.exports.getWolframSpoken = async (question) => {
    return await getWolfram(question, "spoken")
}

module.exports.getWolframShort = async (question) => {
    return await getWolfram(question, "short")
}