"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const console_1 = require("../utils/console");
const api_1 = require("../utils/api");
const validator_1 = require("validator");
const errors_1 = require("../utils/errors");
const fs = require("fs");
const cli_ux_1 = require("cli-ux");
const storage = require("node-persist");
const path = require("path");
const os = require("os");
const GLOBAL_SESSION_PATH = path.join(os.homedir(), ".learnpack-session");
const Session = {
    sessionStarted: false,
    token: null,
    config: null,
    currentCohort: null,
    initialize: async function () {
        if (!this.sessionStarted) {
            // Use a system-wide path instead of config.dirPath
            if (!fs.existsSync(GLOBAL_SESSION_PATH)) {
                fs.mkdirSync(GLOBAL_SESSION_PATH, { recursive: true });
            }
            await storage.init({ dir: GLOBAL_SESSION_PATH });
            this.sessionStarted = true;
        }
        return true;
    },
    setRigoToken: async function (token) {
        await this.initialize();
        const payload = await storage.getItem("bc-payload");
        await storage.setItem("bc-payload", Object.assign(Object.assign({}, payload), { rigobot: { key: token } }));
        console_1.default.debug("Rigobot token successfuly set");
        return true;
    },
    setTabHash: async function (hash) {
        await this.initialize();
        const payload = await storage.getItem("bc-payload");
        await storage.setItem("bc-payload", Object.assign(Object.assign({}, payload), { tabHash: hash }));
        console_1.default.debug("tabHash successfuly set");
        return true;
    },
    setSessionKey: async function (value) {
        await this.initialize();
        const payload = await storage.getItem("bc-payload");
        await storage.setItem("bc-payload", Object.assign(Object.assign({}, payload), { sessionKey: value }));
        console_1.default.debug("sessionKey successfuly set");
        return true;
    },
    setPayload: async function (value) {
        await this.initialize();
        await storage.setItem("bc-payload", Object.assign({}, value));
        console_1.default.debug("Payload successfuly found and set for user " + value.user_id);
        // TelemetryManager.setStudent({
        //   user_id: value.user_id.toString(),
        //   email: value.email,
        //   token: value.token,
        // })
        return true;
    },
    getPayload: async function () {
        await this.initialize();
        let payload = null;
        try {
            payload = await storage.getItem("bc-payload");
        }
        catch (_a) {
            console_1.default.debug("Error retriving session payload");
        }
        return payload;
    },
    isActive: function () {
        return !!this.token;
    },
    get: async function (configObj) {
        if (configObj && configObj.config) {
            this.config = configObj.config;
        }
        await this.sync();
        if (!this.isActive()) {
            return null;
        }
        const payload = await this.getPayload();
        return {
            payload,
            token: this.token,
        };
    },
    login: async function () {
        const email = await cli_ux_1.default.prompt("What is your email?");
        if (!validator_1.default.isEmail(email)) {
            throw (0, errors_1.ValidationError)("Invalid email");
        }
        const password = await cli_ux_1.default.prompt("What is your password?", {
            type: "hide",
        });
        const data = await api_1.default.login(email, password);
        if (data) {
            console_1.default.debug("Login successfull");
            // cli.log(data)
            await this.start({ token: data.token, payload: data });
            return data;
        }
    },
    loginWeb: async function (email, password) {
        if (!validator_1.default.isEmail(email)) {
            throw (0, errors_1.ValidationError)("Invalid email");
        }
        const data = await api_1.default.login(email, password);
        if (data) {
            this.start({ token: data.token, payload: data });
            return data;
        }
    },
    sync: async function () {
        const payload = await this.getPayload();
        if (payload) {
            this.token = payload.token;
        }
    },
    start: async function ({ token, payload = null }) {
        if (!token) {
            throw new Error("A token and email is needed to start a session");
        }
        this.token = token;
        if (payload && (await this.setPayload(payload))) {
            console_1.default.success(`Successfully logged in as user ${payload.user_id}`);
        }
    },
    destroy: async function () {
        if (!this.sessionStarted) {
            await this.initialize();
        }
        await storage.clear();
        this.token = null;
        console_1.default.success("You have logged out");
    },
    breakToken: async function () {
        const payload = await this.getPayload();
        if (payload) {
            this.token = "asdasdasdasd";
            await storage.setItem("bc-payload", Object.assign(Object.assign({}, payload), { token: "asdasdsad" }));
            console_1.default.success("Token broken successfully");
        }
    },
};
exports.default = Session;
