import {Configurator, DocumentDirectory, FileUtils} from './fileutils'
import {loadTemplate, loadTemplateSingle} from "./templates"
import * as path from "path";

const shell = require('electron').shell;
const fs = require('fs');



export class CardModel {
    title: string;
    description: string;
    imgPath: string;
    resourcePath: string;

    constructor(title: string, description: string, imagePath: string, resourcePath: string) {
        this.title = title;
        this.description = description;
        this.imgPath = imagePath;
        this.resourcePath = resourcePath;
    }
}

export function buildFileCard(elem: JQuery<HTMLElement>, obj, append: boolean = false, $: any = require('jquery')) {
    let model = new CardModel(
        obj["title"],
        obj["description"],
        FileUtils.getPathToImage(obj["imagePath"]),
        obj["urlText"]
    );
    model["show"] = obj["show"];

    loadTemplateSingle("web-card.mustache", model, (content: string, id: string) => {
        if (append) {
            elem.append(content);
        } else {
            elem.html(content)
        }

        $(`#${id}`).on("click", () => {
            FileUtils.showFileInDir(model.resourcePath);
        });

        // if (model["show"] !== undefined) {
        //     $(`#${id}`).on("click", () => {
        //         shell.showItemInFolder(model.resourcePath)
        //     });
        // } else {
        //     $(`#${id}`).on("click", () => {
        //         shell.openItem(model.resourcePath)
        //     });
        // }
    });
}

export function buildUiFromConfig(configName: string){
    let elementConfig = Configurator.loadAppConfig(configName);
    let directoryPath = path.join(__dirname, "../assets/resources");
    let fileCards = new DocumentDirectory(directoryPath).getCards();
    buildCardsFromConfig(elementConfig, fileCards);
}

export function buildCardsFromConfig(elementConfig: object, fileCards: Map<string, object>) {
    let $ = require('jquery')
    let containers = Object.keys(elementConfig);

    for (let i = 0, l = containers.length; i < l; i++) {
        let containerName = containers[i];
        let containerObject = elementConfig[containerName];
        let containerElem = $(`#${containerName}`);
        containerElem.html("")
        let containerCategories = Object.keys(containerObject);

        for (let j = 0, m = containerCategories.length; j < m; j++) {
            let categoryMetaObjectKey = containerCategories[j];
            let categoryMetaObject = containerObject[categoryMetaObjectKey];

            let contentList = categoryMetaObject["cards"];//should be array of objects to render
            let files = fileCards.get(categoryMetaObjectKey);

            let categoryDescription = categoryMetaObject["description"];
            let categoryKey = categoryMetaObjectKey.replace(/[\s,]/ig, '-').toLowerCase();
            let categoryObject = {
                "category-description": categoryDescription,
                "category-key": categoryKey,
                "category-id-clean": categoryMetaObjectKey
            };
            let categoryWrapperRaw = loadTemplate("card-category.mustache", categoryObject, (x) => {
            });
            let categoryWrapper = $(categoryWrapperRaw);

            containerElem.append(categoryWrapper);

            let view = $(`#${categoryKey}-container`);
            let collapseButton = $(`#${categoryKey}-collapser`);

            setCollapseOnElement(collapseButton, categoryKey);

            for (let j in files) {
                let file = files[j];
                buildFileCard(view, file, true, $)
            }

            for (let j = 0, m = contentList.length; j < m; j++) {
                let content = contentList[j];
                buildWebCard(view, content, true, $);
            }
        }
    }
}

function setCollapseOnElement(collapseButton: JQuery<HTMLElement>, categoryKey: string){
    collapseButton.on("click", () => {
        let imageMatchRegex = /\.\.\/images\/chevron-(\w+)-(\w+)\.svg$/ig;
        let collapsable = $(`#${categoryKey}-container`);
        let collapseButton = $(`#${categoryKey}-collapser`);
        let collapseImg = $(`#${categoryKey}-img`);
        if ("none" === collapsable.css('display')) {
            collapsable.css("display", "");
            collapseButton.addClass("active");
        } else {
            collapsable.css("display", "none");
            collapseButton.removeClass("active");
        }
        let srcImg = collapseImg.attr("src");
        let groups = imageMatchRegex.exec(srcImg);
        let direction = groups[1];
        let theme = groups[2];
        let newDirection = direction === "up"? "down": "up";
        collapseImg.attr("src", `../images/chevron-${newDirection}-${theme}.svg`);
    });
}

export function buildWebCard(elem: JQuery<HTMLElement>, obj, append: boolean = false, $: any = require('jquery')) {
    let model = new CardModel(
        obj["title"],
        obj["description"],
        FileUtils.getPathToImage(obj["imagePath"]),
        obj["urlText"]
    );

    loadTemplateSingle("web-card.mustache", model, (content: string, id: string) => {
        if (append) {
            elem.append(content);
        } else {
            elem.html(content)
        }

        $(`#${id}`).on("click", () => {
            launchWebsite(obj["urlText"].toString());
        });

    });
}


function fileNameToPrettyString(fileName: string): string {
    let name = fileName.substr(0, fileName.lastIndexOf('.'));
    name = name.replace(/[.\-_]/ig, " ")
    let buffer = name.split('');
    for (let i = 0, l = buffer.length; i < l; i++) {
        if (0 === i || ' ' === buffer[i - 1]) {
            buffer[i] = buffer[i].toUpperCase()
        }
    }
    return buffer.join('');
}

function launchDocument(filename: string) {
    let fullPath = FileUtils.getPathToDocument(filename);
    shell.openItem(fullPath);
}

function launchWebsite(url: string) {
    shell.openItem(url);
}

