import { config } from "./config";
import * as I from "../types/types";
import Utils from "./utils";
import * as Cart from "./cart";
import * as JSC from "./jsc";

export function convertLegendToDropdown(inID: string): void {
    jQuery('ul.seatCharts-legendList').each(function () {
        let select: JQuery<HTMLSelectElement> = jQuery(document.createElement('select'))
            .insertBefore(
                jQuery(this).hide()
            );

        select.attr({ id: inID });
        appendFirstLegendOption(select);
        appendLegendOptions(this, select);
    });
}

export function generateLegend(inNode: string): I.JSCLegend {
    return <I.JSCLegend>{
        node: jQuery(inNode),
        items: createLegendItems()
    }
}

export function dropdownLegendOnChange(inHTMLSelectElement: HTMLSelectElement, inSelector: string) {
    const seatmap: any = config.state.seatmap;
    const sectionID: string = inHTMLSelectElement.value;
    const className: string = `._${sectionID}`;

    changeDropdownLegendBGColor(inSelector, sectionID, className);

    if (sectionID === "all") {
        seatmap.find('unavailable').status('available');
    }
    else {
        seatmap.find('available').status('unavailable');
        JSC.activateSeatsBySectionID(sectionID);
    }

    JSC.setBookedSeatsUnavailable();
    JSC.selectSeatsInCart();
}

function changeDropdownLegendBGColor(inSelector: string, inValue: string, inClassName: string): void {
    return;
    let bgColor: string = "#fafafa";
    let color: string = "#5c5c5c";

    if (inValue !== "all") {
        color = "white";
        bgColor = jQuery(inClassName).css("background-color");
    }

    jQuery(inSelector).css("color", color);
    jQuery(inSelector).css("background-color", bgColor);
    jQuery(`${inSelector} option[value="all"]`).css("color", color);
}

function appendLegendOptions(inElement: HTMLElement, inSelect: JQuery<HTMLSelectElement>): void {
    jQuery('>li', inElement).each(function () {
        const className: string = jQuery(this)[0].children[0].classList[3];
        const val: string = className.substring(1);
        const text: string = (<HTMLElement>jQuery(this)[0].children[1]).innerText;

        appendLegendOption(inSelect, className, val, text);
    });
}

function appendLegendOption(inSelect: JQuery<HTMLSelectElement>, inClass: string, inVal: string, inText: string): void {
    let option: JQuery<HTMLOptionElement> = jQuery('<option/>');
    option.attr({ 'value': inVal, 'data-class': inClass }).text(inText);
    // option.attr({ 'value': inVal, 'class': inClass }).text(inText); // add class to color dropdown bg
    inSelect.append(option);
}

function appendFirstLegendOption(inSelect: JQuery<HTMLSelectElement>): void {
    let option: JQuery<HTMLOptionElement> = jQuery('<option/>');
    option.attr({ 'value': 'all' }).text('Alle Preiskategorien');
    option.css("color", "#5c5c5c");
    inSelect.append(option);
}

function createLegendItems(): string[][] {
    const seatmapXML: any = config.state.seatmapXML;
    const venueXML: I.VenueXML = config.state.inVenueXML!;
    const pricescaleArr: I.SeatmapPricescale[] = seatmapXML.seatmap[0].pricescale_config[0].pricescale;
    const venuePricescaleArr: I.Pricescale2[] = venueXML.venue[0].pricescales[0].pricescale;

    return pricescaleArr.map((arr, index: number) => {
        // feature: get most expensive price so we dont need to rely on ref_price which needs manual entry
        const mostExpensivePrice = venueXML.price_structure[0].pricescale.find(obj => {
            return obj.id[0] === arr.id[0];
        })?.buyer_type.reduce((prev, current) => {
            return (parseFloat(prev.price[0]) > parseFloat(current.price[0])) ? prev : current
        }).price[0];

        const price: string = Cart.getPriceInEur(mostExpensivePrice)!; // changed to highest price instead of ref_price
        const seatsKey: string = String.fromCharCode(97 + index).toLocaleUpperCase();
        const desc: string | undefined = Utils.encodeCP850DecodeUTF8(venuePricescaleArr.find(obj => obj.id[0] === arr.id[0])?.desc[0]!);
        const description: string = `${desc} ${price}`;

        return [seatsKey, "available", description];
    });
}