import axios from "axios";
import {Encrypter} from "./Encrypter";

export class ErrorHandler {

    public static sendError(error: InternalError) {
        let encrypter = new Encrypter("N50LtuKpzOvxp44vaYBFXBQo1tubTY");

        return new Promise<void>((resolve, reject) => {
            let encrypted = Buffer.from(encrypter.encrypt(error.toJson())).toString("base64");

            axios.post('https://itender.gaminggeneration.de/report/send', encrypted, {
                headers: {
                    "Content-Type": "text/plain",
                    Accept: "application/json"
                }
            }).then(res => {
                if (res.status != 200)
                    console.error("Could not send error report");
                else
                    return resolve();

                console.log("Error report was sent to iTender Manager");
            }).catch((e) => console.error);
        });
    }
}

export class InternalError {
    private readonly message: string;
    private readonly stack: string;
    private readonly name: string;

    constructor(message: string, stack: string | undefined, name?: string) {
        this.message = message;
        this.stack = stack ? stack : "";
        this.name = name ? name : "";

        console.error(`\n-------- [INTERNAL ERROR] --------\nName: ${this.name}\nMessage: ${this.message}\nStack: ${this.stack}\n\n`)
    }

    public toJson(): string {
        return JSON.stringify({
            message: this.message,
            stack: this.stack,
            name: this.name,
            date: new Date().toDateString()
        })
    }
}