import * as XMLHelper from "./xmlhelper";
import { config } from "./config";
import * as I from "../types/types";
import * as Events from "./events";
import * as CartButtons from "./cartButtons";
import Utils from "./utils";

export function addItem(inSeatObj: I.JSCSelectedSeat): void { 
    const color: string = `#${XMLHelper.getVenuePricescalePropertyByPricescaleID("color", inSeatObj.data.seatsObj.id[0])}`;
    const category: string | undefined = Utils.encodeCP850DecodeUTF8( XMLHelper.getVenuePricescalePropertyByPricescaleID("desc", inSeatObj.data.seatsObj.id[0])! );
    const seat: string = config.state.layoutRows[inSeatObj.id][5];
    const row: string = config.state.layoutRows[inSeatObj.id][4];
    const sectionID: string = config.state.layoutRows[inSeatObj.id][3];
    const sectionDesc: string | undefined = XMLHelper.getSectionDescBySectionID(sectionID);
    const seatStr: string | undefined = Utils.encodeCP850DecodeUTF8( `${sectionDesc}<br/>Reihe ${row} Platz ${seat}` );
    const buyerTypes: I.TypeBuyerType = XMLHelper.getBuyerTypesByPricescaleID(inSeatObj.data.seatsObj.id[0]);
    const cartID: string = `cartItem-${inSeatObj.id}`;
    const dropdownBuyerTypesSelector: string = `#${cartID} .dropdownBuyerTypes`;

    console.log(category);
    console.log(seatStr);

    appendHTML(cartID, color, category, seatStr);
    addDropdownBuyerTypeOptions(buyerTypes, dropdownBuyerTypesSelector);
    Events.addCartDropdownBuyerTypes(dropdownBuyerTypesSelector, inSeatObj);
}

export function removeCartItems(): void {
    jQuery("#cartItemHTML .cartItem").each(function () {
        this.remove();
    });
}

export function changedDropdownBuyerType(inSelect: HTMLSelectElement, inSeatObj: I.JSCSelectedSeat): void {
    const index: number = config.state.selectedSeatsArr.findIndex(arr =>
        arr[0] === inSeatObj.id);

    config.state.selectedSeatsArr[index][1] = inSelect.value;
    const buyerTypeCode = XMLHelper.getBuyerTypeCodeByBuyerTypeID(inSelect.value);

    if (buyerTypeCode)
        config.state.selectedSeatsArr[index][2] = buyerTypeCode;

    calcOverallPrice();
    CartButtons.setBtnCartText();

    const url = generateCheckoutUrl();
    Events.addRedirectCheckout(url);
}

export function calcOverallPrice(): void{
    if (!config.state.selectedSeatsArr.length)
        config.state.priceOverall = "0";
    else
        config.state.priceOverall = sumSeatPrices();

    config.state.priceOverallEur = getPriceInEur(config.state.priceOverall);
}

export function generateCartItems(): void {
    if (!config.state.selectedSeatsArr.length)
        return;

    for (const key in config.state.selectedSeatsObj) {
        if (Object.prototype.hasOwnProperty.call(config.state.selectedSeatsObj, key)) {
            const element = config.state.selectedSeatsObj[key];
            addItem(element);
        }
    }
}

export function initModalCart(): void {
    jQuery("#modalCart-overlay").hide();
    Events.addCartBack();
    Events.addCartClose();
}

export function generateCheckoutUrl(): string | undefined {
    if (!config.state.selectedSeatsArr.length)
        return;

    const inputsWithValue = config.state.inputsWithValue!;
    const selectedSeatIndexes: string = XMLHelper.generateSelectedSeatIndexes();
    return `${inputsWithValue["ticketPurchaseUrl"]}?user_context=${inputsWithValue.user_context}&pid=${inputsWithValue["pid"]}&selected_seat_indexes=${selectedSeatIndexes}&trxstate=148`;
}

export function getPriceInEur(inPrice: string): string {
    const price: number = parseInt(inPrice);
    return new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(price);
}

export function setImportantNote(): void {
    if (!config.state.inputsWithValue?.importantNote)
        return;

    const importantNoteSelector: JQuery<HTMLElement> = jQuery("#modalCartImportantNote")
    importantNoteSelector[0].innerText = config.state.inputsWithValue?.importantNote
    importantNoteSelector.show();
}

function appendHTML(inCartID: string, inColor: string, inCategory: string | undefined, inSeatStr: string): void {
    jQuery("#cartItemHTML .fl-html").append(`
    <div class="cartItem" id="${inCartID}">
        <div class="cartItemColoredSquare" style="background: ${inColor};"></div>
        <div class="cartItemCategory">${inCategory}</div>
        <h5 class="cartItemSeat">${inSeatStr}</h5>
        <select name="dropdownBuyerTypes" class="dropdownBuyerTypes"></select>
    </div>`);
}

// todo: generalize dropdown fill options
function addDropdownBuyerTypeOptions(inBuyerTypes: I.TypeBuyerType, inSelector: string) {
    if (!inBuyerTypes)
        return;

    inBuyerTypes.forEach(arr => {        
        if (arr[0])
            appendOption(inSelector, arr)
    });
}

function appendOption(inSelector: string, inArr: I.TypeBuyerTypeArr): void {
    const desc: string = Utils.encodeCP850DecodeUTF8( <string>inArr[2] );
    const id: string = <string>inArr[0];
    const price: string = getPriceInEur(<string>inArr[1]);
    const dropdownBuyerTypes: HTMLElement = jQuery(inSelector).get(0);

    console.log(price);
    
    let opt: HTMLOptionElement = document.createElement('option');
    opt.value = id;
    opt.innerHTML = `${desc} ${price}`;
    dropdownBuyerTypes.appendChild(opt);
}

function sumSeatPrices(): string {
    return config.state.selectedSeatsArr.map(getSeatPrice)
        .reduce((prev, curr) => prev + curr)
        .toFixed(2);
}

function getSeatPrice(arr: string[]) {
    const seatID: string = arr[0];
        const buyertypeID: string = arr[1];
        const selectedSeat: I.JSCSelectedSeat = config.state.selectedSeatsObj[seatID];
        const pricescaleID: string = selectedSeat.data.seatsObj.id[0];
        const pricescaleObj: I.Pricescale5 | undefined = XMLHelper.getVenuePriceStructurePropertyByPricescaleID(pricescaleID);

        if (pricescaleObj) {
            const seatPrice: number | undefined = XMLHelper.getPriceByBuyerTypeID(buyertypeID, pricescaleObj);

            if (seatPrice)
                return seatPrice;   
        }

        return 0;
}