import { readFile } from "fs";
import { resolve as res, relative } from "path";

export interface IModules {
    name: string,
    js: HTMLScriptElement,
    css: HTMLLinkElement,
    html: HTMLDivElement
}

/**
 * This script loads or unloads different modules present in src/html
 */
export class Loader {
    content: HTMLDivElement = null;
    head: HTMLHeadElement = null;
    modules: Array<IModules> = null;

    constructor(content: HTMLDivElement) {
        this.content = content;
        this.head = document.getElementsByTagName("head")[0];
        this.modules = [];
    }

    async load(module_name: string) {
        return new Promise<Boolean>((resolve, reject) => {
            // Load css file
            const css = document.createElement("link");
            css.setAttribute("rel", "stylesheet");
            css.setAttribute("href", "../css/" + module_name + ".css");
            this.head.appendChild(css);

            const html_path: string = res("src/html/", module_name + ".html");

            // Load html file
            readFile(html_path, 'utf8', (err, data) => {
                if (err) {
                    console.error("Error while loading html module:", module_name, "(", html_path, ")", err);
                    resolve(false);
                }
                else {
                    this.content.innerHTML += data;

                    // Load js file
                    const js = document.createElement("script");
                    js.setAttribute("type", "text/javascript");
                    js.setAttribute("src", "../js/" + module_name + ".js");
                    this.head.appendChild(js);
                    
                    // Push to loaded modules
                    const mod: IModules = { name: module_name, js: js, css: css, html: <HTMLDivElement>document.getElementById(module_name) };
                    this.modules.push(mod);

                    resolve(true);
                }
            });
        });
    }

    unload(module_name) {
        this.modules.forEach(element => {
            if (element.name == module_name) {
                console.log(element);
                
                element.html.remove();
                element.css.remove();
                element.js.remove();
                return;
            }
            console.error("Tried to remove module which is not loaded:", module_name);
        });
    }
}