import { h, Host } from "@stencil/core";
import { MarketWebContextService } from "../../../globals/MarketWebContextService";
import { FetchHelper } from "../../../globals/FetchHelper";
import debounce from "debounce";
import { translations } from "./translations";
import { alert_exclamation_circle } from "pn-design-assets/pn-assets/icons";
export class PnAddressAutofill {
    constructor() {
        this.market = null;
        this.environment = null;
        this.endpoint = null;
        this.cache = true;
        this.countryCode = null;
        this.language = null;
        this.postalCodeProps = null;
        this.cityProps = null;
        this.streetAddressProps = null;
        this.streetNumberProps = null;
        this.addressNotFoundError = null;
        this.postalCode = null;
        this.city = null;
        this.streetAddress = null;
        this.streetNumber = null;
        this.validAddress = true;
        this.translation = undefined;
        this.postalCodeRequiredLabel = null;
        this.streetRequiredLabel = null;
        this.fullAddress = null;
        this.isLoading = true;
    }
    hostElement;
    pnInputPostalCode = null;
    pnInputCity = null;
    pnInputStreetAddress = null;
    pnInputStreetNumber = null;
    postalCodeInputField = null;
    streetAddressInputField = null;
    streetNumberInputField = null;
    pnInputHiddenValue = null;
    endpointPath = '/api/location/get-by-postalcode';
    _postalCodeProps = null;
    _cityProps = null;
    _streetAddressProps = null;
    _streetNumberProps = null;
    addresscomplete;
    fetchHelper = new FetchHelper('PostalCodeCityAutofill');
    componentWillLoad() {
        this.setInitialValues();
        this._postalCodeProps = this.setProps(this.postalCodeProps);
        this._cityProps = this.setProps(this.cityProps);
        this._streetAddressProps = this.setProps(this.streetAddressProps);
        this._streetNumberProps = this.setProps(this.streetNumberProps);
    }
    setProps(props) {
        if (typeof props === 'string') {
            return JSON.parse(props);
        }
        else {
            return props;
        }
    }
    componentDidLoad() {
        this.postalCodeInputField = this.pnInputPostalCode.querySelector('input');
        this.streetAddressInputField = this.pnInputStreetAddress.querySelector('input');
        this.streetNumberInputField = this.pnInputStreetNumber.querySelector('input');
        this.addEventHandlers();
    }
    async setInitialValues(href = window.location.href) {
        const marketWebContextService = new MarketWebContextService(href);
        if (!this.environment) {
            this.environment = await marketWebContextService.getEnvironmentName();
        }
        if (!this.endpoint && this.environment?.indexOf('local') === -1) {
            this.endpoint = await marketWebContextService.getEndpoint(this.environment, this.market);
        }
        if (!this.endpoint) {
            this.endpoint = '';
        }
        if (!this.language) {
            this.language = await marketWebContextService.getLanguage();
        }
        this.setTranslations();
        this.postalCodeRequiredLabel = "";
        this.streetRequiredLabel = "";
        if (this._postalCodeProps.postalCodeInputRequired === true) {
            this.postalCodeRequiredLabel = " (" + this.translation.required + ")";
        }
        if (this._streetAddressProps.streetAddressInputRequired === true) {
            this.streetRequiredLabel = " (" + this.translation.required + ")";
        }
    }
    setTranslations() {
        if (this.language === 'nb') {
            this.language = 'no';
        }
        if (this.language && translations[this.language]) {
            this.translation = translations[this.language];
        }
    }
    addEventHandlers() {
        let debounceTimeout;
        this.postalCodeInputField.addEventListener('input', (e) => {
            this.isLoading = true;
            clearTimeout(debounceTimeout);
            debounceTimeout = window.setTimeout(() => {
                this.fetchPostalCodeData(e);
            }, 300);
        });
        this.streetNumberInputField.addEventListener('input', debounce(this.fetchAddress.bind(this), 300));
        this.streetAddressInputField.addEventListener('keydown', () => { this.streetNumberInputField.value = ''; });
        this.addFormFieldEvent();
    }
    addFormFieldEvent() {
        const allInputs = this.hostElement.querySelectorAll('input');
        allInputs.forEach(element => {
            ['keyup', 'change', 'blur'].forEach(eventName => {
                const debounceUpdate = debounce(this.updateHiddenValue.bind(this), 1000);
                element.addEventListener(eventName, debounceUpdate);
            });
        });
    }
    updateHiddenValue(e) {
        if (e.target === this.streetNumberInputField) {
            this.streetNumber = this.streetNumberInputField.value;
        }
        if (this.validAddress && this.postalCode && this.city && this.streetAddress && this.streetNumber) {
            this.fullAddress = `${this.streetAddress} ${this.streetNumber}, ${this.city} ${this.postalCode}`;
        }
        else {
            this.fullAddress = '';
        }
        this.addresscomplete.emit(this.fullAddress);
    }
    async fetchPostalCodeData(e) {
        if (!e) {
            return;
        }
        const postalCode = this.postalCodeInputField.value;
        var postalCodeLength = 4;
        if (postalCode.length < postalCodeLength) {
            this.resetFields();
            return;
        }
        if (this.postalCode === postalCode) {
            return;
        }
        this.resetFields();
        this.postalCode = postalCode;
        var data = (await this.fetchPostalCode(postalCode));
        if (!data || !data.addresses) {
            this.city = null;
            this.isLoading = true;
            return;
        }
        const cityInfo = data.addresses?.find(addr => addr.postalCode === postalCode);
        this.city = cityInfo?.city || null;
        this.isLoading = false;
    }
    async fetchPostalCode(postalCode) {
        const endpointBase = this.endpoint.endsWith('/')
            ? this.endpoint.slice(0, -1)
            : this.endpoint;
        const fetchUrl = `${endpointBase}${this.endpointPath}?countryCode=${this.countryCode}&postalCode=${postalCode}`;
        try {
            const data = await this.fetchHelper.fetchJson(fetchUrl, { mode: 'cors' }, this.cache);
            if (!data?.addresses?.length) {
                this.pnInputPostalCode.setAttribute('error', this._postalCodeProps.postalCodeInputError);
                return;
            }
            return data;
        }
        catch (error) {
            console.error("Error fetching address data:", error);
            this.isLoading = true;
            return null;
        }
    }
    resetFields() {
        this.streetAddressInputField.value = '';
        this.streetNumberInputField.value = '';
        this.city = null;
        this.streetAddress = null;
        this.streetNumber = null;
        this.validAddress = false;
        let inputs = document.getElementsByTagName('pn-input');
        Array.from(inputs).forEach(element => {
            element.removeAttribute('error');
        });
    }
    async fetchAddress() {
        const streetAddress = this.streetAddressInputField.value.trim();
        const streetNumber = this.streetNumberInputField.value.trim();
        if (!streetAddress || !streetNumber) {
            this.validAddress = false;
            return;
        }
        const endpointBase = this.endpoint.endsWith('/')
            ? this.endpoint.slice(0, -1)
            : this.endpoint;
        const fetchUrl = `${endpointBase}${this.endpointPath}?countryCode=${this.countryCode}&postalCode=${this.postalCodeInputField.value}&address=${streetAddress + " " + streetNumber}`;
        try {
            const data = await this.fetchHelper.fetchJson(fetchUrl, { mode: 'cors' }, this.cache);
            if (!data?.addresses?.length) {
                this.validAddress = false;
            }
            else {
                const inputStreetAddress = this.normalizeChar(streetAddress);
                const inputStreetNumber = this.normalizeChar(streetNumber);
                const addressFound = data.addresses.some(addr => this.normalizeChar(addr.street) === inputStreetAddress &&
                    this.normalizeChar(addr.houseNumber) === inputStreetNumber &&
                    addr.postalCode === this.postalCodeInputField.value);
                this.validAddress = addressFound;
            }
        }
        catch (error) {
            console.error("Error fetching address data:", error);
            this.isLoading = true;
            this.validAddress = false;
        }
        if (this.streetAddress === streetAddress && this.streetNumber === streetNumber) {
            return;
        }
        if (streetAddress) {
            this.streetAddress = streetAddress;
        }
        if (streetNumber) {
            this.streetNumber = streetNumber;
        }
    }
    //this function is added to compare the street input values if entered without special characters like é, ø ect
    normalizeChar(str) {
        const specialCharMap = {
            'ø': 'o',
            'Ø': 'o',
            'æ': 'ae',
            'Æ': 'ae',
            // Add more as needed
        };
        var str1 = str.normalize("NFD").replace(/[\u0300-\u036f]/g, "")
            .split('').map(char => specialCharMap[char] || char)
            .join('').toLowerCase();
        return str1;
    }
    render() {
        return (h(Host, { key: '43ca8acceb3c02a3a12a6c4da9ae4e4b12853709', class: "pn-address-autofill" }, this._postalCodeProps?.postalCodeCityLabel ? (h("div", { class: "label-container" }, h("label", null, `${this._postalCodeProps.postalCodeCityLabel + ' ' + this.postalCodeRequiredLabel}`))) : null, h("div", { key: '4c61dd29dc1b53a71ab04f79a405bda5323764ab', class: "input-container-row" }, h("pn-input", { key: 'fd0baf1681bc21da522310f1233e693aa3f490cf', type: "number", name: this._postalCodeProps?.postalCodeInputName, required: this._postalCodeProps?.postalCodeInputRequired, placeholder: this._postalCodeProps?.postalCodeInputPlaceholder, ref: el => (this.pnInputPostalCode = el), autocomplete: "off", helpertext: this._postalCodeProps?.postalCodeInputHelpertext }), h("pn-input", { key: 'daa23faa30b9b48969b3f58e09ef6fe29a1f666d', type: "text", name: this._cityProps?.cityInputName, disabled: true, value: this.city, placeholder: this._cityProps?.cityInputPlaceholder, autocomplete: "off", helpertext: this._cityProps?.cityInputHelpertext })), this._streetAddressProps?.streetAddressNumberLabel ? (h("div", { class: "label-container" }, h("label", null, `${this._streetAddressProps.streetAddressNumberLabel + ' ' + this.streetRequiredLabel}`))) : null, h("div", { key: 'da8ef7b1eeca53ccbb926260acd2df79b395ee64', class: "input-container-row" }, h("pn-input", { key: 'cfd025d69b0901885da50d5dd7a763171ff96318', type: "text", name: this._streetAddressProps?.streetAddressInputName, required: this._streetAddressProps?.streetAddressInputRequired, value: this.streetAddress, placeholder: this._streetAddressProps?.streetAddressInputPlaceholder, ref: el => (this.pnInputStreetAddress = el), autocomplete: "off", helpertext: this._streetAddressProps?.streetAddressInputHelpertext, disabled: this.isLoading }), h("pn-input", { key: 'f9da42b0af3c7726686393ce1f161ac30d93a8b3', type: "text", name: this._streetNumberProps?.streetNumberInputName, required: this._streetNumberProps?.streetNumberInputRequired, value: this.streetNumber, placeholder: this._streetNumberProps?.streetNumberInputPlaceholder, ref: el => (this.pnInputStreetNumber = el), autocomplete: "off", helpertext: this._streetNumberProps?.streetNumberInputHelpertext, disabled: this.isLoading })), (!this.validAddress && this.streetAddressInputField.value && this.streetNumberInputField.value) ? (h("div", { class: "toast-container" }, h("pn-toast", { text: this.addressNotFoundError ?? this.translation.addressNotFound, appearance: "warning", icon: alert_exclamation_circle }))) : null));
    }
    static get is() { return "pn-address-autofill"; }
    static get originalStyleUrls() {
        return {
            "$": ["pn-address-autofill.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["pn-address-autofill.css"]
        };
    }
    static get properties() {
        return {
            "market": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Specifies which market we want to show (se,dk,fi,no,com)"
                },
                "attribute": "market",
                "reflect": true,
                "defaultValue": "null"
            },
            "environment": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Specifies which environment we're fetching data from. (production, preproduction, integration, localhost)"
                },
                "attribute": "environment",
                "reflect": true,
                "defaultValue": "null"
            },
            "endpoint": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "endpoint",
                "reflect": false,
                "defaultValue": "null"
            },
            "cache": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "cache",
                "reflect": false,
                "defaultValue": "true"
            },
            "countryCode": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "country-code",
                "reflect": false,
                "defaultValue": "null"
            },
            "language": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "language",
                "reflect": false,
                "defaultValue": "null"
            },
            "postalCodeProps": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string | PostalCodeProps",
                    "resolved": "PostalCodeProps | string",
                    "references": {
                        "PostalCodeProps": {
                            "location": "import",
                            "path": "./types",
                            "id": "src/components/input/pn-address-autofill/types.ts::PostalCodeProps"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "postal-code-props",
                "reflect": false,
                "defaultValue": "null"
            },
            "cityProps": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string | CityProps",
                    "resolved": "CityProps | string",
                    "references": {
                        "CityProps": {
                            "location": "import",
                            "path": "./types",
                            "id": "src/components/input/pn-address-autofill/types.ts::CityProps"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "city-props",
                "reflect": false,
                "defaultValue": "null"
            },
            "streetAddressProps": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string | StreetAddressProps",
                    "resolved": "StreetAddressProps | string",
                    "references": {
                        "StreetAddressProps": {
                            "location": "import",
                            "path": "./types",
                            "id": "src/components/input/pn-address-autofill/types.ts::StreetAddressProps"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "street-address-props",
                "reflect": false,
                "defaultValue": "null"
            },
            "streetNumberProps": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string | StreetNumberProps",
                    "resolved": "StreetNumberProps | string",
                    "references": {
                        "StreetNumberProps": {
                            "location": "import",
                            "path": "./types",
                            "id": "src/components/input/pn-address-autofill/types.ts::StreetNumberProps"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "street-number-props",
                "reflect": false,
                "defaultValue": "null"
            },
            "addressNotFoundError": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "address-not-found-error",
                "reflect": false,
                "defaultValue": "null"
            }
        };
    }
    static get states() {
        return {
            "postalCode": {},
            "city": {},
            "streetAddress": {},
            "streetNumber": {},
            "validAddress": {},
            "translation": {},
            "postalCodeRequiredLabel": {},
            "streetRequiredLabel": {},
            "fullAddress": {},
            "isLoading": {}
        };
    }
    static get events() {
        return [{
                "method": "addresscomplete",
                "name": "addresscomplete",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                }
            }];
    }
    static get elementRef() { return "hostElement"; }
}
//# sourceMappingURL=pn-address-autofill.js.map
