import * as I from "../types/types";
import { config } from "./config";
var jQuery = require("jquery");
import Utils from './utils';

export function getVenueLocation(): string {
    let spanArr: string[] = [];
    jQuery(".venue span").each(function (this: any) {
        spanArr.push(jQuery(this).text());
    });

    return spanArr.join(", ");
}

export function getInputs(inContent: string): I.Inputs  {
    const parsedHTML: Node[] = jQuery.parseHTML(inContent);
    let inputs: I.Inputs = {};

    jQuery(parsedHTML).find('input').each(function (this: any) {
        const name: string = this.name;
        const value: string = this.value;

        if (value !== '')
            inputs[name] = value;
    });

    return inputs;
}

// todo: check with different venues
export function getImportantNote(): I.ImportantNote | undefined  {
    if (jQuery(".important_note").length) {
        const importantNote: string | null = jQuery(".important_note")[0].textContent;

        if (importantNote?.trim().length) {
            const importantNoteEncoded: string = encodeURIComponent(importantNote);
            return <I.ImportantNote> {
                "importantNote": importantNote,
                "importantNoteEncoded": importantNoteEncoded
            }        
        }
    }   

    return undefined;
}

export function getAdditionalInputs(inContent: string): I.Inputs {
    const event = inContent.match(/event:"(.+?)"/)![1];
    const holdcode = inContent.match(/holdcode:"(.+?)"/)![1];
    const posturlRaw = inContent.match(/posturl:"(.+?)"/)![1];
    const posturlRawDecoded = decodeURIComponent(posturlRaw);
    const posturl = decodeURIComponent(`${posturlRaw}&event=${event}&holdcode=${holdcode}&nocache=0&inclpkg=Y&incloffer=Y&inclcartdetails=Y&inclCart=Y&inclvenue=Y`);
    const venueLocation = getVenueLocation();
    const ticketPurchaseUrl = `${posturlRawDecoded.split("?")[0].split('/').slice(0,-1).join('/')}/TicketPurchase`;

    return <I.Inputs> {
        "event": event,
        "holdcode": holdcode,
        "posturlRaw": posturlRaw,
        "posturlRawDecoded": posturlRawDecoded,
        "posturl": posturl,
        "venueLocation": venueLocation,
        "ticketPurchaseUrl": ticketPurchaseUrl
    }    
}

export function getVenueImage(): I.VenueImage | undefined {
    const img: HTMLImageElement = jQuery("#static_venue_map img").get(0);

    if (img) {
        return <I.VenueImage> {
            venueImageSrc: img.src,
            venueImageHeight: img.height,
            venueImageWidth: img.width
        }
    }
    
    return undefined;
}

export function getSMAP(): string | undefined {
    if (!jQuery("#seating_map_url").length)
        return undefined;

    const str: string = jQuery("#seating_map_url a").attr("onclick");
    const re = /openNewWindow\(\'(\d+)\'/;
    const found: RegExpMatchArray | null = str.match(re);
 
    return found ? found[1] : undefined;
}

export function getEventInfo(): I.EventInfo {
    const venueXML: I.VenueXML = config.state.inVenueXML!;
    const sectionArr: I.Section2[] = venueXML.master_config[0].section_inventory[0].section;
    const eventObj: I.Event = venueXML.event[0];
    const event: I.Event = venueXML.event[0];
    const venue_config: I.VenueConfig = venueXML.venue_config[0];
    const dateObj: Date = new Date(parseInt(event.year[0]), parseInt(event.month[0]) - 1, parseInt(event.day[0]), parseInt(event.hour[0]), parseInt(event.minute[0]));
    const start: string[] = [dateObj.toLocaleString(["de-DE"], { weekday: "long", day: "2-digit", month: "2-digit", year: "numeric", hour: "2-digit", minute: "2-digit", timeZoneName: "short" })];
    const weekday: string[] = [Utils.getDayName(dateObj, "de-DE")];
    const seats_available = sectionArr.map(item => parseInt(item.available[0])).reduce((prev, curr) => prev + curr);

    const eventExtend: I.EventExtend = {
        venue_config_capacity: venue_config.capacity,
        venue_config_code: venue_config.code,
        venue_config_desc: venue_config.desc,
        venue_config_id: venue_config.id,
        venue_config_nav_image: venue_config.nav_image,
        venue_config_nav_image_height: venue_config.nav_image_height,
        venue_config_nav_image_width: venue_config.nav_image_width,
        start: start,
        weekday: weekday,
        seats_available: seats_available,
    };

    return <I.EventInfo>{ ...eventObj, ...eventExtend };
}