import { config } from "./config";
import * as I from "../types/types";

export function addTrims(): void {
    const seatmapXML: any = config.state.seatmapXML;
    const trimArr: I.Trim[] = seatmapXML.seatmap[0].trims[0].trim;

    trimArr.forEach(arr => {
        const [xTrim, yTrim] = arr.coord[0].split(",").map(Number);
        const textArr: string[] = arr.text[0].split(";").filter(Boolean);
        const x: number = xTrim / 20;
        const y: number = Math.round(yTrim / 21.25);        

        decodeTrim(textArr, x, y);
    });
}

function decodeTrim(textArr: string[], x: number, y: number): void {
    const specialChar: Map<string, string> = new Map([
        ["&#x8e", "Ä"],
        ["&#x99", "Ö"],
        ["&#x9a", "Ü"],
        ["&#x84", "ä"],
        ["&#x94", "ö"],
        ["&#x81", "ü"],
        ["&#xe1", "ß"]
    ]);

    textArr.map((element, index) => {
        const character: string | undefined = specialChar.has(element) ? specialChar.get(element) : decodeNormalTrim(element);

        if (character) {
            const trimPos: I.TrimPos = getJSCTrimPos(x, y, index);
            applyTrim(character, trimPos);
        }            
    });
}

function decodeNormalTrim(element: string): string {
    const charCode: string = element.replace(/^\&\#/, "0");
    return String.fromCharCode(parseInt(charCode, 16));
}

function applyTrim(inCharacter: string, inTrimPos: I.TrimPos): void {
    const regex: RegExp = /[^a-zA-Z0-9äöüÄÖÜß$]/;
    
    if (!regex.test(inCharacter)) {
        console.log(`${inCharacter} -> ${inTrimPos.xJSC} ${inTrimPos.yJSC}`);
        jQuery(".seatCharts-row")[inTrimPos.yJSC].children[inTrimPos.xJSC].innerHTML = `<span class="trimChar">${inCharacter}</span>`
    }
}

function getJSCTrimPos(inX: number, inY: number, index: number): I.TrimPos {
    return <I.TrimPos> {
        x: inX,
        y: inY,
        xJSC: (inX - 1) + index,
        yJSC: inY - 1
    }
}