import { h, Host } from "@stencil/core";
import { translations } from "./translations";
import { PEX_truck } from "pn-design-assets/pn-assets/illustrations.js";
export class PnPexPricefinder {
    constructor() {
        this.language = 'sv';
        this.currency = 'Kr';
        this.apiUrl = '/api/pex/order';
        this.i18n = translations.sv;
        this.fromzip = null;
        this.tozip = null;
        this.weight = 1;
        this.when = '';
        this.response = null;
    }
    hostElement;
    componentWillLoad() {
        this.init();
    }
    async init() {
        this.setInitialTime();
        this.checkParameters();
        this.setLanguage();
    }
    setInitialTime() {
        const initialTime = new Date();
        initialTime.setHours(initialTime.getHours() + 1);
        initialTime.setMinutes(0);
        const splitTime = initialTime.toLocaleString('sv', { timeZoneName: 'short' }).split(' ');
        this.when = `${splitTime[0]}T${splitTime[1].substring(0, 5)}`;
    }
    checkParameters() {
        const params = new URLSearchParams(window.location.href);
        if (!params) {
            return;
        }
        const paramKeys = ['fromzip', 'tozip', 'weight', 'when'];
        paramKeys.forEach(key => {
            if (params.get(key)) {
                this[key] = params.get(key);
            }
        });
    }
    setLanguage() {
        if (translations[this.language]) {
            this.i18n = translations[this.language];
        }
    }
    onSubmit(e) {
        e.preventDefault();
        const formData = new FormData(e.target);
        const requestQuery = this.compileRequestQuery(formData);
        this.fetchResult(requestQuery);
    }
    compileRequestQuery(formData) {
        let query = {
            from: formData.get('fromzip'),
            to: formData.get('tozip'),
            weight: formData.get('weight'),
            when: formData.get('when'),
        };
        if (!query.when) {
            query.when = this.hostElement.querySelector('input.date-input').value;
        }
        if (!formData.get('fromzip') || !formData.get('tozip') || !formData.get('weight')) {
            console.error('Form data is not compliant');
            return;
        }
        return query;
    }
    async fetchResult(query) {
        this.response = null;
        const params = new URLSearchParams(query);
        const req = await fetch(`${this.apiUrl}?${params.toString()}`, {
            method: 'get',
            headers: {
                'Content-Type': 'application/json',
            },
        }).catch(this.onFetchError.bind(this));
        let response = await req.json().catch(this.onFetchError.bind(this));
        if (!response) {
            response = await (await import('./mockresponse.json')).default;
        }
        if (response) {
            this.response = response;
        }
    }
    onFetchError(error) {
        console.error('onFetchError(error', error);
    }
    render() {
        return (h(Host, { key: '07ebd8d6255c1152a3c391462055d5de2cc732fd' }, h("div", { key: 'da47c58cdbf755ee85bc5a951f8b9f5811279097', class: "pex-pricefinder-top" }, h("pn-illustration", { key: '47edf0059307429874abb8847f1f8e4e705f945f', illustration: PEX_truck }), h("h2", { key: '62c2de74f8faad097c11349908d9392178a0f4f7' }, this.i18n.heading)), h("form", { key: '08678b12dee5299dbdea1567ebd244b3643b26f7', method: "get", action: "", class: "pex-pricefinder-form", onSubmit: this.onSubmit.bind(this) }, h("fieldset", { key: '9b4ccb866040e402630130d0c2d6c3d0fda95789' }, h("div", { key: '1c6a287986bbad27e96307f70a0301bdb104aecb' }, h("pn-input", { key: '36a46d8941bc7d0b9b52e76d50208664f8b84336', type: "number", label: this.i18n.labelFrom, inputid: "fromzip", name: "fromzip", placeholder: this.i18n.zipPlaceholder, required: true, value: this.fromzip }), h("pn-input", { key: 'e05764b4de7dbd58148e073097047a4326afa92e', type: "number", label: this.i18n.labelTo, inputid: "tozip", name: "tozip", placeholder: this.i18n.zipPlaceholder, required: true, value: this.tozip }))), h("fieldset", { key: 'f41afe2b0fe4d6aaaf7e77b78c0fd240d6a963c5' }, h("div", { key: '2a6a2785b70b4a3d4d78bc9c18ef31d7902442cf' }, h("pn-input", { key: 'b2e1b8fde55ad622c4b09954a7039cd40d405c3a', type: "number", label: this.i18n.labelWeight, inputid: "weight", name: "weight", placeholder: this.i18n.weightPlaceholder, required: true, value: this.weight }), h("div", { key: '68361172baa45049917667b4f5a02d9b1d9155ae', class: "datepicker" }, h("label", { key: '390e0c47251f75ea230c3c6ef54b6e081193a7af', htmlFor: "when" }, this.i18n.labelWhen), h("pn-marketweb-input", { key: '09da4ba47f8a6b309f790114f4cf123457f55c38', inputid: "when", name: "when", type: "datetime-local", min: new Date().toISOString().split('T')[0], value: this.when })))), h("fieldset", { key: 'def4b4966f36bce8682ae2f1c7c90c315cd8cb17' }, h("div", { key: '072a781a61287d51b515449405fd8c6c5e751b8c' }, h("pn-button", { key: 'e10166d33057271cca7d77efa7e473c6f79d3ec5', type: "submit" }, this.i18n.submitButtonText)))), this.response ? (h("div", { class: "pex-pricefinder-response" }, h("strong", null, this.response.data.value, " ", this.currency))) : null));
    }
    static get is() { return "pn-pex-pricefinder"; }
    static get originalStyleUrls() {
        return {
            "$": ["pn-pex-pricefinder.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["pn-pex-pricefinder.css"]
        };
    }
    static get properties() {
        return {
            "language": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Specifies which language we want to show component in (sv,da,fi,no,en)"
                },
                "attribute": "language",
                "reflect": false,
                "defaultValue": "'sv'"
            },
            "currency": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Currency (Kr, \u20AC)"
                },
                "attribute": "currency",
                "reflect": false,
                "defaultValue": "'Kr'"
            },
            "apiUrl": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "API Url"
                },
                "attribute": "api-url",
                "reflect": false,
                "defaultValue": "'/api/pex/order'"
            }
        };
    }
    static get states() {
        return {
            "i18n": {},
            "fromzip": {},
            "tozip": {},
            "weight": {},
            "when": {},
            "response": {}
        };
    }
    static get elementRef() { return "hostElement"; }
    static get listeners() {
        return [{
                "name": "language",
                "method": "setLanguage",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
//# sourceMappingURL=pn-pex-pricefinder.js.map
