"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.troubleshootOverObservableReducer = exports.troubleshootOverObservable = exports.troubleshoot = void 0;
const errors_1 = require("@ledgerhq/errors");
const axios_1 = __importDefault(require("axios"));
const isomorphic_ws_1 = __importDefault(require("isomorphic-ws"));
const rxjs_1 = require("rxjs");
const live_env_1 = require("@ledgerhq/live-env");
const api_1 = __importDefault(require("../notifications/AnnouncementProvider/api/api"));
const api_2 = __importDefault(require("../notifications/ServiceStatusProvider/api/api"));
// Run all checks and return. each troubleshoot have a promise that suceed if the underlying job worked.
function troubleshoot() {
    // TODO in future, we can delegate a "troubleshoot" per coin implementation.
    return [
        {
            title: "My Ledger services (scriptrunner)",
            translationKey: "troubleshootNetwork.myLedgerServices",
            ...websocketConnects(`${(0, live_env_1.getEnv)("BASE_SOCKET_URL")}/apps/list?targetId=856686596&perso=perso_11&livecommonversion=27.7.2`),
        },
        {
            title: "Bitcoin explorers",
            translationKey: "troubleshootNetwork.bitcoinExplorers",
            ...httpGet((0, live_env_1.getEnv)("EXPLORER") + "/blockchain/v4/btc/block/current"),
        },
        {
            title: "Ethereum explorers",
            translationKey: "troubleshootNetwork.ethereumExplorers",
            ...httpGet((0, live_env_1.getEnv)("EXPLORER") + "/blockchain/v4/eth/block/current"),
        },
        {
            title: "Countervalues API",
            translationKey: "troubleshootNetwork.countervaluesApi",
            ...httpGet(`${(0, live_env_1.getEnv)("LEDGER_COUNTERVALUES_API")}/v3/spot/simple?froms=bitcoin&to=eur`),
        },
        {
            title: "Announcements",
            translationKey: "troubleshootNetwork.announcements",
            technicalDescription: "fetching announcements",
            job: api_1.default.fetchAnnouncements(),
        },
        {
            title: "Status",
            translationKey: "troubleshootNetwork.status",
            technicalDescription: "fetching status",
            job: api_2.default.fetchStatusSummary(),
        },
    ];
}
exports.troubleshoot = troubleshoot;
function httpGet(url) {
    return {
        technicalDescription: "fetching " + url,
        job: axios_1.default.get(url, { timeout: 30000 }),
    };
}
function websocketConnects(url) {
    const job = new Promise((resolve, reject) => {
        const ws = new isomorphic_ws_1.default(url);
        const timeout = setTimeout(() => {
            ws.close();
            reject(new Error("timeout"));
        }, 30000);
        ws.onopen = () => {
            clearTimeout(timeout);
            resolve(url);
            ws.close();
        };
        ws.onerror = e => {
            reject(e);
        };
        ws.onclose = () => {
            reject(new errors_1.WebsocketConnectionError("closed"));
        };
    });
    return {
        technicalDescription: "connecting to " + url,
        job,
    };
}
function troubleshootOverObservable() {
    return new rxjs_1.Observable(o => {
        try {
            const all = troubleshoot();
            o.next({
                type: "init",
                all: all.map(s => ({
                    title: s.title,
                    translationKey: s.translationKey,
                    technicalDescription: s.technicalDescription,
                    status: "loading",
                })),
            });
            let total = 0;
            all.forEach(s => {
                s.job
                    .then(() => {
                    o.next({
                        type: "change",
                        status: {
                            title: s.title,
                            translationKey: s.translationKey,
                            technicalDescription: s.technicalDescription,
                            status: "success",
                        },
                    });
                }, e => {
                    o.next({
                        type: "change",
                        status: {
                            title: s.title,
                            translationKey: s.translationKey,
                            technicalDescription: s.technicalDescription,
                            status: "error",
                            error: String(e?.message || e),
                        },
                    });
                })
                    .then(() => {
                    if (++total === all.length) {
                        o.complete();
                    }
                });
            });
        }
        catch (e) {
            o.error(e);
        }
    });
}
exports.troubleshootOverObservable = troubleshootOverObservable;
function troubleshootOverObservableReducer(state, event) {
    if (event.type === "init") {
        return event.all;
    }
    if (event.type === "change") {
        return state.map(s => (s.title === event.status.title ? event.status : s));
    }
    return state;
}
exports.troubleshootOverObservableReducer = troubleshootOverObservableReducer;
//# sourceMappingURL=index.js.map