import { h } from "@stencil/core";
import { translations, markets } from "./pn-find-price-translations";
import { weights, sizeCategories, fileLocation } from "./data.js";
import { convertFileForSizeCategogy } from "../../../globals/shared/productprice/convert.js";
import { state } from "./pn-find-price-store";
import small from "./img/small-package.svg";
import medium from "./img/medium-package.svg";
import large from "./img/large-package.svg";
import person from "./img/postnord-person1.svg";
import clouds from "./img/clouds.svg";
export class PnfindPrice {
    constructor() {
        this.source = fileLocation;
        this.language = 'sv';
        this.market = 'se';
        this.filteredItems = [];
        this.weight = { value: 0, name: '' };
        this.weightvalue = 0;
        this.sourceData = { types: [], data: [] };
        this.sizecategory = { value: '', name: '', icon: '', unit: '' };
    }
    componentWillLoad() {
        this.setState();
        this.getDataSource();
    }
    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 convertFileForSizeCategogy(reqbody);
            this.sourceData = convertedData;
            //for keeping small value preselected
            this.sizecategory = sizeCategories.filter(x => x.value === 'Small')[0];
            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() {
        if (!this.sourceData?.data) {
            console.log('Data has not yet been loaded');
            return;
        }
        //to handle withing country search
        const deliveryScopeData = this.sourceData.data.filter(x => x.deliveryscope.toLocaleLowerCase() === state.market.country.toLocaleLowerCase());
        if (!this.sizecategory) {
            return;
        }
        const sizeItemData = deliveryScopeData.filter(x => x.sizecategory.toLocaleLowerCase() === this.sizecategory.value.toLocaleLowerCase());
        if (!this.weight) {
            return;
        }
        const comparisonWeight = this.weight.value <= 20 ? this.weight.value * 1000 : this.weight.value;
        let weightFilteredData = sizeItemData.filter(x => (x.maxweight <= 20 ? x.maxweight * 1000 : x.maxweight) === comparisonWeight);
        if (this.weightvalue !== 0) {
            let clubbedProducts = sizeItemData
                .filter(x => x.maxweight.toString().includes('upto'))
                .filter(x => Number(x.maxweight.toString().toLocaleLowerCase().replace('upto', '')) - comparisonWeight >= 0);
            weightFilteredData = weightFilteredData.concat(clubbedProducts);
        }
        if (weightFilteredData.length === 0 && this.weightvalue !== 0) {
            weightFilteredData = sizeItemData.filter(x => (x.maxweight <= 20 ? x.maxweight * 1000 : x.maxweight) >= comparisonWeight);
            if (weightFilteredData.length > 0) {
                //sort based on the maxvalue
                weightFilteredData.sort((a, b) => {
                    return a.maxweight - b.maxweight;
                });
                // map to get the next unique item
                const uniqueWeightOptions = [...new Map(weightFilteredData.reverse().map(item => [item['id'], item])).values()];
                if (uniqueWeightOptions.length > 0) {
                    weightFilteredData = uniqueWeightOptions;
                }
            }
        }
        //10000 to handle the null values in the rank column, to keep such products at the end of the list
        weightFilteredData.sort((a, b) => {
            var ra = a.rank ? a.rank : 10000;
            var rb = b.rank ? b.rank : 10000;
            var ua = a.highestrankusp ? a.highestrankusp : 'z';
            var ub = b.highestrankusp ? b.highestrankusp : 'z';
            const compareUsp = ua.localeCompare(ub);
            const compareRank = ra - rb;
            return compareUsp || compareRank;
        });
        this.filteredItems = weightFilteredData;
    }
    render() {
        return (h("div", { key: '1d83da6b02b97a358ac624274e23327425021881', class: "findprice-form" }, h("fieldset", { key: '5397d6ed6b45b9e62bc77daabd8ef37b79e3fc1b' }, h("legend", { key: 'e2eccc63568642955ee091206748ea8f0e782d3c', class: "heading" }, state.i18n.sizeheading), h("div", { key: '68f1039882f0066e2669994bc03a01790b235b94', class: "sizecategory" }, h("table", { key: '7cda02f149431d7023c86a74b9a9e4d6a7b7e970', class: "sizeTable" }, h("img", { key: '1347d8df9b11259f7366bcc40a0d43fc9f02c334', id: "clouds", src: clouds }), h("tr", { key: '92cd6c7463294fa22c28ae1c9a8ff1720d9d36b5' }, h("td", { key: 'a196790e22196e6883f93281469f845959c278a3' }, h("img", { key: '39b4f6d3c5c7753dad3baf44f0b2181c6d3f20be', class: "firstCell", src: person })), h("td", { key: '18df7943ef469dd5c006123cc3c4a854c9aeaec9' }, h("img", { key: 'f542102147239b98f1e5badac416e98f04a029a2', src: small })), h("td", { key: '6d254cb13fe79792d75260c55571babba8be240f' }, h("img", { key: 'f4d33734b8463364d881f8ea89a32aba6fb8b225', src: medium })), h("td", { key: '10f727f4642740fb36383d46db7f2a1934d36cae' }, h("img", { key: 'fe644f43c78035a32d5a4244ec1d0bd64df4385f', src: large }))), h("tr", { key: '79486d239522adba8e6331c9fefc4ffcd62758ea' }, h("td", { key: 'feac9e89feee808253b422d51d231e41ac3d9f5b' }), sizeCategories.map(sizeCategory => (h("td", null, h("pn-radio-button", { id: 'findpricecategory-' + sizeCategory.value, radioid: sizeCategory.value, value: sizeCategory.value, name: "sizecategory", checked: sizeCategory.value === this.sizecategory.value, onChange: () => {
                this.sizecategory = sizeCategories.filter(x => x.value === sizeCategory.value)[0];
                this.weight = { value: 0, name: '' };
                this.weightvalue = this.weight.value;
            } })))))))), h("fieldset", { key: '7429534bdbadef6704acc7a900d06d1a976825bc' }, h("legend", { key: '1e2c491db6bf124f282c89a6e5b2c05512630485', class: "heading" }, state.i18n.weightheading), this.sizecategory.value && weights[this.sizecategory.unit] ? (h("div", { class: "weightoption" }, h("div", { class: "weightoption-content" }, weights[this.sizecategory.unit].map(wght => (h("pn-choice-button", { id: 'findpriceweight-' + wght.value, choiceid: this.sizecategory.value + wght.value, name: "weight", type: "radio", value: !this.weight.value ? 0 : weights[this.sizecategory.unit].findIndex(x => x.value === this.weightvalue), checked: wght.value === this.weight.value, onChange: () => {
                this.weight = weights[this.sizecategory.unit].filter(x => x.value === wght.value)[0];
                this.weightvalue = this.weight.value;
            } }, wght.name)))))) : null, this.filteredItems && this.filteredItems.length > 0 ? (h("div", { class: "resultlist" }, state.i18n.resultlistheading ? h("div", { class: "resultHeading" }, state.i18n.resultlistheading) : null, this.filteredItems.map((item) => (h("div", null, h("pn-find-price-result", { item: item })))))) : null)));
    }
    static get is() { return "pn-find-price"; }
    static get originalStyleUrls() {
        return {
            "$": ["pn-find-price.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["pn-find-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": "fileLocation"
            },
            "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": {},
            "weight": {},
            "weightvalue": {},
            "sourceData": {},
            "sizecategory": {}
        };
    }
    static get watchers() {
        return [{
                "propName": "market",
                "methodName": "setState"
            }, {
                "propName": "language",
                "methodName": "setState"
            }, {
                "propName": "sizecategory",
                "methodName": "filterItems"
            }, {
                "propName": "weightvalue",
                "methodName": "filterItems"
            }];
    }
}
//# sourceMappingURL=pn-find-price.js.map
