import { h, Host } from "@stencil/core";
import { translations, markets } from "./pn-product-pricelist-translations";
import { weights } from "./data.js";
import { convertFileFromStream } from "../../../globals/shared/productprice/convert.js";
// import { state } from "./pn-product-pricelist-store";
import { state } from "../pn-find-price/pn-find-price-store";
export class PnFindProductPricelist {
    constructor() {
        this.source = 'https://com-inte.postnord.com/globalassets/global/prices/sv-findprice-1-PN.xlsx';
        this.language = 'sv';
        this.market = 'se';
        this.productid = '';
        this.filteredItems = [];
        this.sourceData = { types: [], data: [] };
        this.gotData = false;
        this.loading = false;
        this.postagetype = { value: '' };
        this.weight = { value: 0, name: '' };
        this.weightvalue = 0;
    }
    componentWillLoad() {
        this.setState();
        this.getDataSource().then(() => { });
    }
    setState() {
        if (this.market) {
            state.market = markets[this.market];
        }
        if (this.language && translations[this.language]) {
            state.i18n = translations[this.language];
        }
    }
    async getDataSource() {
        if (!this.productid) {
            return;
        }
        this.loading = true;
        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) {
            this.loading = false;
            console.warn('Unable to parse data');
        }
    }
    filterItems() {
        if (!this.sourceData?.data) {
            console.info('Data has not yet been loaded');
            return;
        }
        this.loading = false;
        const productIdItems = this.sourceData.data.filter(x => x.id === this.productid);
        if (productIdItems.length === 0) {
            return;
        }
        this.postagetype.value = productIdItems[0].what;
        if (!weights[this.postagetype.value] || weights[this.postagetype.value].length === 0) {
            return;
        }
        if (this.weightvalue === 0) {
            this.weight = weights[this.postagetype.value][0];
            this.weightvalue = this.weight.value;
        }
        // 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 = productIdItems.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 = productIdItems.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;
        this.gotData = this.filteredItems.length > 0;
    }
    render() {
        return (h(Host, { key: 'bc5342bd9146d1a2c4e6f7452a3819f6d52bf1d8' }, h("div", { key: '1b36f58ccf4039e8f627d399771833771915a66b', class: "content" }, h("slot", { key: '718cd122baaa9be3e59bccab68557d74f63f515b' })), this.loading ? h("pn-spinner", null) : null, this.postagetype.value && weights[this.postagetype.value] ? (h("div", { class: "weightselection" }, 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, h("div", { key: '1276f72147dd62396be53a819fc9d393f3b5af6b', class: "resultlist", "data-list-count": this.filteredItems.length }, this.filteredItems.map((item) => (h("div", null, h("pn-find-price-result", { item: item })))))));
    }
    static get is() { return "pn-product-pricelist"; }
    static get originalStyleUrls() {
        return {
            "$": ["pn-product-pricelist.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["pn-product-pricelist.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-findprice-1-PN.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'"
            },
            "productid": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "productid",
                "reflect": false,
                "defaultValue": "''"
            }
        };
    }
    static get states() {
        return {
            "filteredItems": {},
            "sourceData": {},
            "gotData": {},
            "loading": {},
            "postagetype": {},
            "weight": {},
            "weightvalue": {}
        };
    }
    static get watchers() {
        return [{
                "propName": "market",
                "methodName": "setState"
            }, {
                "propName": "language",
                "methodName": "setState"
            }, {
                "propName": "postagetype",
                "methodName": "filterItems"
            }, {
                "propName": "weightvalue",
                "methodName": "filterItems"
            }];
    }
}
//# sourceMappingURL=pn-product-pricelist.js.map
