import { config } from "./config";
import axios from 'axios';
import * as Communication from "./communication";
import * as I from "../types/types";

export function needCheckoutResponse(inE: any, inInputsWithValue: I.InputsWithValue) {
    const data: I.Message = JSON.parse(inE.data);
    const inUrl: string = data.message.url;

    axios.get(inUrl, {
        maxRedirects: 0
    })
        .then((inE) => {
            type orderkey = string | number | string[] | undefined;
            let isValidSeatSelection: boolean = false;
            const content: string = inE.data;
            const parsedHTML: Node[] = jQuery.parseHTML(content);
            const orderkey: orderkey = jQuery(parsedHTML).find("#orderkey").val();

            console.log(`orderkey: ${orderkey}`);

            if (orderkey) {
                isValidSeatSelection = true;
                const cancelUrl = `${inInputsWithValue["ticketPurchaseUrl"]}?user_context=${inInputsWithValue["user_context"]}&pid=${inInputsWithValue["pid"]}&orderkey=${orderkey}&trxstate=92`;
                Communication.cancelCheckout(cancelUrl);
            }

            const message: I.Message = {
                message: {
                    "isValidSeatSelection": isValidSeatSelection,
                    "parsedHTML": parsedHTML,
                    "url": inUrl,
                },
                from: "parent",
                event: "parent_sendCheckoutResponse",
                date: Date.now()
            };
            Communication.sendMessage(message, "iframeSeatmap");
        })
        .catch(function (error) {
            console.log("error in child_needCheckoutResponse");
            console.log(error);
        });
}

export function initNeedInputsWithValue(inInputsWithValue: I.InputsWithValue) {
    const message: I.Message = {
        message: inInputsWithValue,
        from: "parent",
        event: "parent_init_sendInputsWithValue",
        date: Date.now()
    };
    Communication.sendMessage(message, "iframeSeatmap");
}

export function initNeedVenueXML(inInputsWithValue: I.InputsWithValue) {
    Communication.sendXML(inInputsWithValue["posturl"], "iframeSeatmap", "parent_init_sendVenueXML", "parent");
    config.childHasVenueXML = true;
}

export function needSeatmapXML(inE: any, inInputsWithValue: I.InputsWithValue) {
    const data: I.Message = JSON.parse(inE.data);
    const seatmapUrl: string = `${inInputsWithValue["posturlRawDecoded"]}&inclseatmap=Y&seatmap=${data.message}`;
    Communication.sendXML(seatmapUrl, "iframeSeatmap", "parent_sendSeatmapXML", "parent");
}

export function clickCheckout(inE: any) {
    const data: I.Message = JSON.parse(inE.data);
    const inUrl: string = data.message.url;
    window.location.href = inUrl;
}