import { h } from "@stencil/core";
import { translations, markets } from "./pn-find-service-and-price-translations";
import { postagetypes, weights, deliveryscopes } from "./data.js";
import { convertFileFromStream } from "../../../globals/shared/productprice/convert.js";
import { state } from "./pn-find-service-and-price-store";
export class PnfindServiceAndPrice {
    constructor() {
        this.source = 'https://com-inte.postnord.com/globalassets/global/prices/sv-se-findprice.xlsx';
        this.language = 'sv';
        this.market = 'se';
        this.filteredItems = [];
        this.postagetype = {
            value: '',
            name: '',
            icon: '',
        };
        this.weight = { value: 0, name: '' };
        this.weightvalue = 0;
        this.deliveryscope = {
            value: '',
            name: '',
            icon: '',
        };
        this.sourceData = { types: [], data: [] };
    }
    componentWillLoad() {
        this.setState();
        this.getDataSource();
        // window.setTimeout(() => {
        //   this.postagetype = postagetypes[0];
        //   this.deliveryscope = deliveryscopes[this.postagetype.value][0];
        //   this.weight = weights[this.postagetype.value][0];
        //   this.weightvalue = this.weight.value;
        // }, 500)
    }
    async getDataSource() {
        const cacheBusting = `?cache=${Math.floor(Math.random() * (10000 - 1) + 1)}`;
        const req = await fetch(this.source + cacheBusting);
        const reqbody = await req.blob();
        try {
            const convertedData = await convertFileFromStream(reqbody);
            this.sourceData = convertedData;
            this.filterItems();
        }
        catch (e) {
            console.log('Unable to parse data');
        }
    }
    setState() {
        if (this.market) {
            state.market = markets[this.market];
        }
        if (this.language && translations[this.language]) {
            state.i18n = translations[this.language];
        }
    }
    filterItems() {
        // this.debug = `Postagetype: ${this.postagetype.value}. <br/>Weight: ${ this.weight.value }`;
        if (!this.sourceData?.data) {
            console.log('Data has not yet been loaded');
            return;
        }
        if (!this.postagetype) {
            return;
        }
        const typeData = this.sourceData.data.filter(x => x.what === this.postagetype.value);
        if (!this.deliveryscope) {
            return;
        }
        const deliveryScopeData = typeData.filter(x => x.deliveryscope === this.deliveryscope.value);
        if (!this.weight || !this.weight.value) {
            return;
        }
        // For letters we use grams. Otherwise we use KG
        const comparisonWeight = this.weight.abbreviation.toLocaleLowerCase() === 'kg' && this.postagetype.value === 'letter' ? this.weight.value * 1000 : this.weight.value;
        let weightFilteredData = deliveryScopeData.filter(x => x.maxweight === comparisonWeight);
        // In parcels the maxwidths don't necessarily start at 1kg so we fetch any type below the user selected value
        if (weightFilteredData.length === 0) {
            weightFilteredData = deliveryScopeData.filter(x => x.maxweight >= comparisonWeight);
            if (weightFilteredData.length > 0) {
                // We reverse the result array since the map will take the last unique item instead of the first
                const uniqueWeightOptions = [...new Map(weightFilteredData.reverse().map(item => [item['id'], item])).values()];
                if (uniqueWeightOptions.length > 0) {
                    weightFilteredData = uniqueWeightOptions;
                }
            }
        }
        this.filteredItems = weightFilteredData;
    }
    render() {
        return (h("div", { key: '51cd3bdb7327102e9da2121b7a0938173b928d77' }, h("div", { key: 'c5ab609c11853cc7f1c494b70780b9b901cb64db', class: "findprice-form" }, state.i18n.componentheading ? h("h2", null, state.i18n.componentheading) : null, h("div", { key: 'e888f71144a581259fc7fdb743b316a69a016419', class: "postagetypes" }, postagetypes.map(postagetype => (h("pn-choice-button", { choiceid: postagetype.value, value: postagetype.value, name: "postagetype", type: "radio", checked: postagetype.value === this.postagetype.value, onChange: () => {
                this.postagetype = postagetypes.filter(x => x.value === postagetype.value)[0];
                this.deliveryscope = { value: '', name: '', icon: '' };
                this.weight = { value: 0, name: '' };
                this.weightvalue = this.weight.value;
            } }, h("pn-illustration", { illustration: postagetype.illustration }), " ", postagetype.name)))), this.postagetype.value && deliveryscopes[this.postagetype.value] ? (h("div", null, state.i18n.deliveryscopeheading ? h("div", { class: "heading" }, state.i18n.deliveryscopeheading) : null, h("div", { class: "deliveryscope" }, deliveryscopes[this.postagetype.value].map(deliveryscope => (h("pn-choice-button", { choiceid: this.postagetype.value + deliveryscope.value, value: deliveryscope.value, name: "deliveryscope", type: "radio", checked: deliveryscope.value === this.deliveryscope.value, onChange: () => {
                this.deliveryscope = deliveryscopes[this.postagetype.value].filter(x => x.value === deliveryscope.value)[0];
                if (this.weight.value === 0) {
                    this.weight = weights[this.postagetype.value][0];
                    this.weightvalue = this.weight.value;
                }
            } }, h("pn-illustration", { illustration: deliveryscope.illustration }), " ", deliveryscope.name)))))) : null, this.postagetype.value && weights[this.postagetype.value] && this.deliveryscope.value ? (h("div", null, state.i18n.sizeheading ? h("div", { class: "heading" }, state.i18n.sizeheading) : null, h("div", { class: "weightoption" }, h("div", { class: "weightoption-input" }, h("pn-input", { inputid: "weightvalue", name: "weightvalue", type: "number", label: state.i18n.weightlabel, value: this.weightvalue, onChange: e => {
                if (e && e.target && e.target.value) {
                    const weightNum = parseInt(e.target.value, 10);
                    if (!isNaN(weightNum)) {
                        let matchingWeights = weights[this.postagetype.value].filter(x => {
                            let weightInGrams = x.abbreviation === 'kg' ? x.value * 1000 : x.value;
                            return weightInGrams >= weightNum;
                        });
                        if (matchingWeights && matchingWeights.length > 0) {
                            this.weight = matchingWeights[0];
                            this.weightvalue = this.weight.value;
                        }
                    }
                }
            } }), h("span", { class: "weightoption-input-abbreviation" }, this.weight.abbreviation)), h("div", { class: "weightoption-range" }, h("input", { type: "range", id: "weightrange", name: "weightrange", list: "weightlist", value: !this.weight.value ? 0 : weights[this.postagetype.value].findIndex(x => x.value === this.weightvalue), onChange: e => {
                const value = e.target.value;
                this.weight = weights[this.postagetype.value][value];
                this.weightvalue = this.weight.value;
            }, min: "0",
            // max={ weights[this.postagetype.value][weights[this.postagetype.value].length - 1].value }
            max: weights[this.postagetype.value].length - 1 }), h("datalist", { id: "weightlist" }, weights[this.postagetype.value].map((weight, weightindex) => {
            let labelText = weight.name;
            if (weights[this.postagetype.value].length > 6) {
                labelText = weightindex % 5 === 0 || weightindex === 0 || weightindex === weights[this.postagetype.value].length - 1 ? weight.name : '';
            }
            return h("option", { value: weightindex, ...(labelText ? { label: labelText } : {}) });
        })))))) : null), this.filteredItems && this.filteredItems.length > 0 ? (h("div", { class: "resultlist" }, state.i18n.resultlistheading ? h("div", { class: "heading" }, state.i18n.resultlistheading) : null, this.filteredItems.map((item) => (h("div", null, h("pn-find-service-and-price-result", { item: item })))))) : null));
    }
    static get is() { return "pn-find-service-and-price"; }
    static get originalStyleUrls() {
        return {
            "$": ["pn-find-service-and-price.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["pn-find-service-and-price.css"]
        };
    }
    static get properties() {
        return {
            "source": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "source",
                "reflect": false,
                "defaultValue": "'https://com-inte.postnord.com/globalassets/global/prices/sv-se-findprice.xlsx'"
            },
            "language": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "language",
                "reflect": false,
                "defaultValue": "'sv'"
            },
            "market": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "market",
                "reflect": false,
                "defaultValue": "'se'"
            }
        };
    }
    static get states() {
        return {
            "filteredItems": {},
            "postagetype": {},
            "weight": {},
            "weightvalue": {},
            "deliveryscope": {},
            "sourceData": {}
        };
    }
    static get watchers() {
        return [{
                "propName": "market",
                "methodName": "setState"
            }, {
                "propName": "language",
                "methodName": "setState"
            }, {
                "propName": "postagetype",
                "methodName": "filterItems"
            }, {
                "propName": "deliveryscope",
                "methodName": "filterItems"
            }, {
                "propName": "weightvalue",
                "methodName": "filterItems"
            }];
    }
}
//# sourceMappingURL=pn-find-service-and-price.js.map
