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

export function addSeatToState(inSelectedSeat: I.JSCSelectedSeat): void {
    addSeatObjToState(inSelectedSeat);
    const pricescaleID: string = config.state.selectedSeatsObj[inSelectedSeat.id].data.seatsObj.id[0];
    const pricescaleObj: I.Pricescale5 | undefined = XMLHelper.getVenuePriceStructurePropertyByPricescaleID(pricescaleID);

    if (pricescaleObj) {
        const firstBuyerTypeID: string = pricescaleObj.buyer_type[0].id[0];
        const buyerTypeCode: string | undefined = XMLHelper.getBuyerTypeCodeByBuyerTypeID(firstBuyerTypeID);
        const selectedSeatsArrItem: (string | undefined)[] = [inSelectedSeat.id, firstBuyerTypeID, buyerTypeCode];
        addSeatsItemToState(selectedSeatsArrItem);
    }
    else
        console.warn(`Cannot find corresponding venueXML pricescaleObj for pricescale with ID ${pricescaleID}`);
}

export function removeSeatFromState(inSelectedSeat: I.JSCSelectedSeat): void {
    delete config.state.selectedSeatsObj[inSelectedSeat.id];

    const index: number = config.state.selectedSeatsArr.findIndex(arr => arr[0] === inSelectedSeat.id);
    config.state.selectedSeatsArr.splice(index, 1);

    config.state.cartChanged = true;

    if (!config.state.selectedSeatsArr.length)
        jQuery("#modalCart-overlay").hide();
}

export function maximumSelectedSeatsReached(inSeatObj: I.JSCSelectedSeat): boolean {
    const seatmap: any = config.state.seatmap;

    if (config.state.selectedSeatsArr.length >= config.maxSelectedSeats) {
        jBoxHelper.showJBoxNotice(`Sie können maximal ${config.maxSelectedSeats} Plätze auswählen.`);
        seatmap.status(inSeatObj.id, "available");
        return true;
    }

    return false;
}

function addSeatsItemToState(inItem: (string | undefined)[]): void {
    if (inItem.every(v => v !== ("" || undefined || null))) {
        config.state.selectedSeatsArr.push(<string[]>inItem);
        config.state.cartChanged = true;
    }
}

function addSeatObjToState(inSelectedSeat: I.JSCSelectedSeat): void {
    const seatID: string = inSelectedSeat.id;
    const seatObj: I.StateJSCSelectedSeats = {
        [seatID]: inSelectedSeat
    }

    config.state.selectedSeatsObj = { ...config.state.selectedSeatsObj, ...seatObj }
}