const $ = require('jquery');
import {ConfigPaths, Configurator} from "./fileutils";

export module Themes {
    export enum AppTheme {
        Light = "theme-light",
        Dark = "theme-dark"
    }

    export function initTheme() {
        let conf = Configurator.loadUserConfig(ConfigPaths.UserConfigName);
        let initTheme = conf['theme'];
        applyTheme(initTheme);
        let initToggle = $('#theme-toggle');
        let initThemeEnum = getThemeFromValue(initTheme);
        initToggle.addClass(getButtonClassFromAppTheme(initThemeEnum));
        initToggle.on("click", () => {
            let conf = Configurator.loadUserConfig(ConfigPaths.UserConfigName);
            let toggle = $("#theme-toggle");
            let themeValue = conf['theme'];
            let currTheme = getThemeFromValue(themeValue);
            let opposite = getOppositeTheme(currTheme);
            toggle.removeClass(getButtonClassFromAppTheme(currTheme));
            toggle.addClass(getButtonClassFromAppTheme(opposite));
            applyTheme(opposite);
            conf['theme'] = opposite;
            Configurator.saveUserConfig(ConfigPaths.UserConfigName, conf);
        });
    }

    export function applyTheme(name: string) {
        let head = $('head');
        let newResource = `styles/${name}.css`;
        let headLinks = head.children("link")
        let themePattern = /theme-.*\.css/ig;
        for (let i = 0, l = headLinks.length; i < l; i++) {
            let link = headLinks[i];
            if (themePattern.test(link.href)) {
                link.remove();
            }
        }
        head.prepend(buildCSSLink(newResource));
    }

    function getButtonClassFromAppTheme(t: AppTheme): string {
        switch (t) {
            case Themes.AppTheme.Dark:
                return "btn-light";
            case Themes.AppTheme.Light:
                return "btn-dark";
        }
    }

    function getThemeFromValue(v: string): AppTheme {
        switch (v) {
            case AppTheme.Light:
                return AppTheme.Light;
            case AppTheme.Dark:
                return AppTheme.Dark;
        }
    }

    function getOppositeTheme(t: AppTheme): AppTheme {
        switch (t) {
            case Themes.AppTheme.Dark:
                return Themes.AppTheme.Light;
            case Themes.AppTheme.Light:
                return Themes.AppTheme.Dark;
        }
    }


    function buildCSSLink(resourceName: string): HTMLElement {
        let link = $("<link>", {rel: "stylesheet", href: resourceName})
        return link as HTMLElement
    }
}

Themes.initTheme();
