import {Configurator, FileUtils} from './fileutils'
import {loadTemplateSingle} from "./templates"
const shell = require('electron').shell;

const config = new Configurator();
const fu = new FileUtils();

class CardModel {
    imagePath: string;
    fileName: string;

    constructor(path: string, name: string) {
        this.imagePath = path;
        this.fileName = name;
    }
}

export function buildFileCard(filePath: string, elem: Element, append: boolean = false) {
    let model = new CardModel(getImagePathFromDocumentName(filePath), fileNameToPrettyString(filePath));
    loadTemplateSingle("file-card", model, (content: string, id: string) => {
        if (append) {
            elem.innerHTML = elem.innerHTML + content;
        } else {
            elem.innerHTML = content;
        }
        document.querySelector("#" + id).addEventListener('click', ()=>{
            launchDocument(filePath);
        })
    });
}

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 getImagePathFromDocumentName(name: string): string {
    return fu.getPathToImage(config.getFileExtensionToImageMap()[fu.getFileExtension(name)])
}

function launchDocument(filename) {
    let fullPath = fu.getPathToDocument(filename);
    shell.openItem(fullPath);
}

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