import { h } from "@stencil/core";
import { translations, markets } from "./pn-proxio-findprice-translations";
import { MarketWebContextService } from "../../../globals/MarketWebContextService";
import { weights, sizeCategories } from "./data.js";
import { FetchHelper } from "../../../globals/FetchHelper";
import { state } from "./pn-proxio-findprice-store";
import S from "./img/small-package.svg";
import M from "./img/medium-package.svg";
import L from "./img/large-package.svg";
import person from "./img/postnord-person2.svg";
import clouds from "./img/clouds.svg";
import { trash_can } from "pn-design-assets/pn-assets/icons.js";
export class PnProxioFindPrice {
    constructor() {
        this.endpoint = null;
        this.language = 'da';
        this.market = 'dk';
        this.showMedium = false;
        this.showInternational = false;
        this.maxAbroadKg = 0;
        this.weightListName = '';
        this.cache = false;
        this.filteredItems = [];
        this.weight = { value: 0, name: '' };
        this.weightvalue = 0;
        this.countrycodevalue = '';
        this.sizecategory = { value: '', name: '', icon: '', unit: '' };
        this.data = { proxioProducts: [], shipmentCountries: [] };
    }
    fetchHelper = new FetchHelper('proxiopricegroups');
    componentWillLoad() {
        this.setInitialValues().then(() => {
            this.init();
        });
    }
    async setInitialValues(href = window.location.href) {
        const marketWebContextService = new MarketWebContextService(href);
        const environment = await marketWebContextService.getEnvironmentName();
        if (!this.endpoint && environment?.indexOf('local') === -1) {
            const market = await marketWebContextService.getMarket();
            this.market = this.market ? this.market : market;
            this.endpoint = await marketWebContextService.getEndpoint(environment, market);
        }
        if (!this.endpoint) {
            this.endpoint = '';
        }
        if (this.countrycodevalue === '') {
            this.countrycodevalue = this.market.toLowerCase();
        }
    }
    init() {
        this.setState();
        this.fetchData().then(() => {
            this.getDataSource();
        });
    }
    async getDataSource() {
        try {
            this.sizecategory = sizeCategories.filter(x => x.value === 'S')[0];
            this.filterItems();
        }
        catch (e) {
            console.log('Unable to parse data');
        }
    }
    async fetchData() {
        if (!this.market || !this.language) {
            return;
        }
        const endpoint = this.endpoint.lastIndexOf('/') === this.endpoint.length - 1 ? this.endpoint.substring(0, this.endpoint.length - 1) : this.endpoint;
        const fetchUrl = `${endpoint}/api/proxio/price-list-groups?market=${this.market}&language=${this.language}&cached=${this.cache}`;
        //const fetchUrl = `https://localhost:51547/api/proxio/price-list-groups?market=${this.market}&language=${this.language}&cached=${this.cache}`;
        const data = (await this.fetchHelper.fetchJson(fetchUrl, {
            mode: 'cors',
        }, false, this.onFetchData.bind(this)));
        if (data) {
            this.data = data;
            this.data.proxioProducts = data.proxioProducts;
        }
        this.filterItems();
    }
    onFetchData(data) {
        this.data = data;
    }
    setState() {
        this.market = this.market ? this.market : 'dk';
        if (this.market) {
            state.market = markets[this.market];
        }
        if (this.language && translations[this.language]) {
            state.i18n = translations[this.language];
        }
    }
    filterItems() {
        const sizeItemData = this.data.proxioProducts.filter(item => {
            return item.proxioProduct.productWeightGroupList.some(weightGroup => {
                return weightGroup.item3.includes(this.sizecategory.value);
            });
        });
        if (!this.weight) {
            return;
        }
        const comparisonWeight = this.weight.value;
        let weightFilteredData = sizeItemData?.filter(item => {
            return item.proxioProduct.productWeightGroupList.some(weightGroup => {
                return weightGroup.item1 === comparisonWeight;
            });
        });
        let isInternational = this.showInternational && ((this.countrycodevalue?.trim() ?? '') !== '');
        if (isInternational) {
            weightFilteredData = weightFilteredData?.filter(item => item.proxioProduct.weightPriceCountryList.some(countryItem => countryItem.item3.includes(this.countrycodevalue.toUpperCase())));
        }
        weightFilteredData = this.sortWeightItems(weightFilteredData, isInternational);
        this.filteredItems = weightFilteredData;
    }
    parseFloatFromString(text) {
        return parseFloat(text?.replace(/[^\d\.\,]*/g, '') ?? 100000);
    }
    sortWeightItems(weightFilteredData, isInternational) {
        weightFilteredData?.sort((a, b) => {
            let aNumber = this.getSortNumber(a, isInternational);
            let bNumber = this.getSortNumber(b, isInternational);
            if (aNumber && bNumber) {
                return aNumber - bNumber;
            }
            if (aNumber < bNumber) {
                return -1;
            }
            if (aNumber > bNumber) {
                return 1;
            }
            return 0;
        }) ?? [];
        return weightFilteredData;
    }
    getSortNumber(proxioPriceListGroupResponseItem, isInternational) {
        let index = proxioPriceListGroupResponseItem?.proxioProduct?.productWeightGroupList?.findIndex(weightGroup => weightGroup.item1 === this.weight.value) ?? 0;
        if (index < 0) {
            index = 0;
        }
        let pricevalue = proxioPriceListGroupResponseItem?.proxioProduct?.weightAndPriceList[index]?.item2?.toLowerCase() ?? '';
        if (isInternational) {
            let weightPriceCurrentCountryList = proxioPriceListGroupResponseItem?.proxioProduct?.weightPriceCountryList?.filter(countryItem => countryItem.item3.includes(this.countrycodevalue.toUpperCase()));
            pricevalue = weightPriceCurrentCountryList[index]?.item2?.toLowerCase() ?? '';
        }
        let sortNumber = this.parseFloatFromString(pricevalue);
        return sortNumber;
    }
    resetFilters() {
        this.weight = { value: 0, name: '' };
        this.sizecategory = sizeCategories.filter(x => x.value === 'S')[0];
        this.weightvalue = 0;
        this.countrycodevalue = this.data?.shipmentCountries[0]?.countryCode ?? this.market;
    }
    getWeights() {
        let weightListName = this.market + this.weightListName;
        let marketWeightsArray = weights[weightListName] ?? { S: [], M: [], L: [] };
        let marketWeights = marketWeightsArray[this.sizecategory.unit];
        let isInternationalWeights = this.maxAbroadKg != 0 && this.countrycodevalue.toLowerCase() !== this.market.toLowerCase();
        marketWeights = isInternationalWeights ? marketWeights.filter(number => number.value / 1000 <= this.maxAbroadKg) : marketWeights;
        return marketWeights;
    }
    handleDropdownChange(event) {
        const target = event.target;
        const countryCode = target.value;
        this.countrycodevalue = countryCode;
    }
    render() {
        return (h("div", { key: 'eccc1a9866fc1a495b5e5b6c1516b72c4e539d72', class: "findprice-form" }, h("div", { key: '88211adbd41bb2f54ac7163805586113bde24a91', class: "findprice-form-wrapper" }, h("fieldset", { key: 'a2d9036d946f6f20d9caafcb5d523eabbc94a5fc' }, h("legend", { key: 'f29865751978b79ce7060a5e6916f280333940c3', class: "findprice__heading" }, state.i18n.sizeheading), h("div", { key: 'da21a9113c7d9606c31bcd940abbc3f4a88ba492', class: "sizecategory" }, h("table", { key: '49e537b528bb2033c876fe32cb69f3472f431397', class: "sizeTable" }, h("img", { key: '07e0ef277879c0898f0d1663adb12ed523156768', id: "clouds", src: clouds, alt: state.i18n.cloudsImage }), h("tr", { key: '0a8d72aaf438cb1dcd5c81c2388e125221bf87fc' }, h("td", { key: 'cb451c8711e487d9e313c964e6a083cdcdb63024' }, h("img", { key: '3357bff5a6d50e10bda00e1761f682d3f7d6741b', class: "firstCell", src: person, alt: state.i18n.personComparison })), h("td", { key: '3da0256ccb45f92ac978c66256066f50864a79e8' }, h("img", { key: '50415e18db434f26a3e8946f291b300eaf547307', src: S, alt: state.i18n.smallPackage })), this.showMedium ? (h("td", null, h("img", { src: M, alt: state.i18n.mediumPackage }))) : null, h("td", { key: 'b02ae797011d26174abb61790061f2c60060f093' }, h("img", { key: '6f2fe93b306e922ef00510ea1d7fca8e5c513230', src: L, alt: state.i18n.largePackage }))), h("tr", { key: 'de8d0788a5b0b1f05bd36da0014ca8147a7173be' }, h("td", { key: 'ba6aa89a0fdd1eec4f3a1eb484fffc785d4f921d' }), sizeCategories.map(sizeCategory => !this.showMedium && sizeCategory.value === 'M' ? null : (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: '2517e6de768636cd03b01b2a73f5a352944a1976' }, h("legend", { key: 'd04a87b771ee8050d4a7a6a1fb86938fc00e6334', class: "findprice__heading findprice__subheading" }, state.i18n.weightheading), this.sizecategory.value && this.getWeights() ? (h("div", { class: "weightoption" }, h("div", { class: "weightoption-content" }, this.getWeights().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 : this.getWeights().findIndex(x => x.value === this.weightvalue), checked: wght.value === this.weight.value, onChange: () => {
                this.weight = this.getWeights().filter(x => x.value === wght.value)[0];
                this.weightvalue = this.weight.value;
            } }, wght.name)))))) : null), this.showInternational && (this.data?.shipmentCountries ?? false) ? (h("fieldset", null, h("div", { class: "shipmentcountry" }, h("legend", { class: "shipmentcountry-header" }, state.i18n.countryToSendTo), h("div", { class: "shipmentcountry-select-container" }, h("svg", { class: "arrow", width: "18", height: "10", viewBox: "0 0 18 10", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, h("path", { "fill-rule": "evenodd", "clip-rule": "evenodd", d: "M9.70711 9.70711C9.31658 10.0976 8.68342 10.0976 8.29289 9.70711L0.292892 1.70711C-0.0976315 1.31658 -0.0976315 0.683417 0.292892 0.292893C0.683418 -0.0976315 1.31658 -0.0976315 1.70711 0.292893L9 7.58579L16.2929 0.292893C16.6834 -0.0976315 17.3166 -0.0976315 17.7071 0.292893C18.0976 0.683417 18.0976 1.31658 17.7071 1.70711L9.70711 9.70711Z" })), h("select", { name: "shipmentCountry-select", id: "proxio-shipmentcountry", onChange: this.handleDropdownChange.bind(this) }, this.data.shipmentCountries.map(item => (h("option", { selected: item.countryCode.toLowerCase() === this.countrycodevalue.toLowerCase(), value: item.countryCode }, item.countryName)))))))) : null, h("div", { key: '6ae2a8721447bea1fb9ccb9a24d0d9fc5cc0c785', class: "findprice__clear-all-filters", role: "button" }, h("div", { key: '2836a349989162d60b40f05bd6a782284af545d0', class: "findprice__clear-all-filters__btn", onClick: () => this.resetFilters() }, h("pn-icon", { key: '92f29a652851bc7dc2515ab44bf492037feb9aed', icon: trash_can, color: "blue700" }), h("span", { key: '857ee8395e91d28bacc7d41215d189a9fdbb2bbe', class: "clear-all-filters__text" }, state.i18n.clearFilterButton)))), 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-proxio-findprice-result", { activeweight: this.weight.value, item: item, language: this.language, "selected-countrycode": this.countrycodevalue, "show-international": this.showInternational, market: this.market })))))) : this.weightvalue !== 0 ? (h("h4", { class: "resultHeading" }, state.i18n.noResultMessage)) : null));
    }
    static get is() { return "pn-proxio-findprice"; }
    static get originalStyleUrls() {
        return {
            "$": ["pn-proxio-findprice.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["pn-proxio-findprice.css"]
        };
    }
    static get properties() {
        return {
            "endpoint": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "endpoint",
                "reflect": false,
                "defaultValue": "null"
            },
            "language": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "language",
                "reflect": false,
                "defaultValue": "'da'"
            },
            "market": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "market",
                "reflect": false,
                "defaultValue": "'dk'"
            },
            "showMedium": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "show-medium",
                "reflect": false,
                "defaultValue": "false"
            },
            "showInternational": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "show-international",
                "reflect": false,
                "defaultValue": "false"
            },
            "maxAbroadKg": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "max-abroad-kg",
                "reflect": false,
                "defaultValue": "0"
            },
            "weightListName": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "weight-list-name",
                "reflect": false,
                "defaultValue": "''"
            },
            "cache": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "cache",
                "reflect": false,
                "defaultValue": "false"
            }
        };
    }
    static get states() {
        return {
            "filteredItems": {},
            "weight": {},
            "weightvalue": {},
            "countrycodevalue": {},
            "sizecategory": {},
            "data": {}
        };
    }
    static get watchers() {
        return [{
                "propName": "market",
                "methodName": "setState"
            }, {
                "propName": "language",
                "methodName": "setState"
            }, {
                "propName": "sizecategory",
                "methodName": "filterItems"
            }, {
                "propName": "weightvalue",
                "methodName": "filterItems"
            }, {
                "propName": "countrycodevalue",
                "methodName": "filterItems"
            }];
    }
}
//# sourceMappingURL=pn-proxio-findprice.js.map
