import { hasAnswerChanged, shouldHideQuestion } from "@boldpenguin/sdk-utility";
import { h } from "@stencil/core";
export class BpSdkAddressGroup {
    constructor() {
        this.updateInputs = (address) => () => {
            this.updateStreet(address);
            this.updateCity(address);
            this.updateState(address);
            this.updateZip(address);
        };
        /**
         * Emits addressMissingComponents event if any required
         * address components are missing
         *
         * @param addressComponents The array of address components from Google
         */
        this.handleMissingAddressComponents = (addressComponents) => {
            const missingComponents = this.getMissingAddressComponents(addressComponents);
            if (missingComponents.length) {
                this.addressMissingComponents.emit({
                    missing_components: missingComponents,
                });
            }
        };
        /**
         * Finds the address components that are missing in the Google data
         *
         * @param addressComponents The array of address components from Google
         * @returns Returns an array of missing address component types
         */
        this.getMissingAddressComponents = (addressComponents) => {
            const requiredAddressComponentTypes = ['street_number', 'route', 'locality', 'administrative_area_level_1', 'postal_code'];
            return requiredAddressComponentTypes.filter((requiredAddressComponentType) => {
                return !addressComponents.some((addressComponent) => addressComponent.types[0] === requiredAddressComponentType);
            });
        };
        this.answers = [];
        this.label = undefined;
        this.labelledBy = undefined;
        this.disableAutoSave = false;
        this.useAddressValidation = false;
        this.addressValidationId = undefined;
        this.answerMap = {};
        this.useExternal = false;
    }
    onAnswersChange(newAnswers) {
        const map = {};
        newAnswers.forEach((answer) => {
            var _a;
            if ((_a = answer === null || answer === void 0 ? void 0 : answer.question) === null || _a === void 0 ? void 0 : _a.reference_type) {
                map[answer.question.reference_type] = answer;
            }
        });
        this.answerMap = map;
    }
    resetState() { }
    connectedCallback() {
        this.resetState();
    }
    componentWillLoad() {
        this.useExternal = !!customElements.get('bp-sdk-external-address-group');
        customElements.whenDefined('bp-sdk-external-address-group').then(() => {
            this.useExternal = true;
        });
        this.onAnswersChange(this.answers);
    }
    emitSaveAnswer(answer, newValue) {
        if (hasAnswerChanged(answer, newValue)) {
            this.saveAnswer.emit({
                answer,
                new_value: newValue,
            });
        }
    }
    onSaveAnswer(event) {
        if (this.disableAutoSave) {
            this.stageAddressValidationAnswerForUpdate.emit(event.detail);
            event.preventDefault();
            event.stopImmediatePropagation();
        }
    }
    onPlacesUpdate({ detail }) {
        if (this.useExternal) {
            return;
        }
        const address = {};
        if (detail.address_components) {
            detail.address_components.forEach((addressComponent) => {
                address[addressComponent.types[0]] = {
                    short: addressComponent.short_name,
                    long: addressComponent.long_name,
                };
            });
            setTimeout(this.updateInputs(address), 0);
            this.handleMissingAddressComponents(detail.address_components);
        }
        this.updateJson(detail);
    }
    updateStreet(address) {
        if (address['street_number'] && address['route']) {
            const street_answer = this.answerMap['street_1'];
            if (street_answer) {
                this.emitSaveAnswer(Object.assign({}, street_answer), `${address['street_number'].long} ${address['route'].long}`);
            }
        }
    }
    updateCity(address) {
        if (address['locality']) {
            const city_answer = this.answerMap['city'];
            if (city_answer) {
                this.emitSaveAnswer(Object.assign({}, city_answer), address['locality'].long);
            }
        }
    }
    updateState(address) {
        if (address['administrative_area_level_1']) {
            const state_answer = this.answerMap['state'];
            if (state_answer) {
                const state = address['administrative_area_level_1'].short;
                const state_choice = state_answer.question.choices.find((choice) => choice.alias === state);
                if (state_choice) {
                    this.emitSaveAnswer(Object.assign({}, state_answer), [state_choice.id]);
                }
            }
        }
    }
    updateZip(address) {
        if (address['postal_code']) {
            const zip_answer = this.answerMap['zipcode'];
            if (zip_answer) {
                this.emitSaveAnswer(Object.assign({}, zip_answer), address['postal_code'].long);
            }
        }
    }
    updateJson(place) {
        const json_answer = this.answerMap['address_json'];
        if (json_answer) {
            this.emitSaveAnswer(Object.assign({}, json_answer), JSON.stringify(place));
        }
    }
    render() {
        return [this.useExternal && this.renderExternal(), !this.useExternal && this.renderInternal()];
    }
    renderExternal() {
        return h("bp-sdk-external-address-group", { answers: this.answers, label: this.label, labelledBy: this.labelledBy });
    }
    renderInternal() {
        return (h("div", { class: "bp-sdk-address-group__container" }, h("div", { class: "bp-sdk-address-group__streets" }, h("div", { class: "bp-sdk-row" }, this.answerMap['street_1'] && (h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group-street-primary", labelledBy: this.labelledBy, shouldHideLabel: shouldHideQuestion(this.label, this.answerMap['street_1']), answer: this.answerMap['street_1'], disableAddressAutocomplete: this.disableAutoSave })), this.answerMap['street_2'] && (h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group-street-secondary", labelledBy: this.labelledBy, shouldHideLabel: shouldHideQuestion(this.label, this.answerMap['street_2']), answer: this.answerMap['street_2'] })))), (this.answerMap['city'] || this.answerMap['state'] || this.answerMap['zipcode']) && (h("div", { class: "bp-sdk-address-group__locality" }, h("div", { class: "bp-sdk-row" }, this.answerMap['city'] && (h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group__city", labelledBy: this.labelledBy, shouldHideLabel: shouldHideQuestion(this.label, this.answerMap['city']), answer: this.answerMap['city'] })), this.answerMap['state'] && (h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group__state", labelledBy: this.labelledBy, shouldHideLabel: shouldHideQuestion(this.label, this.answerMap['state']), answer: this.answerMap['state'], useSelectAlias: true })), this.answerMap['zipcode'] && (h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group__zipcode", labelledBy: this.labelledBy, shouldHideLabel: shouldHideQuestion(this.label, this.answerMap['zipcode']), answer: this.answerMap['zipcode'] }))))), this.answerMap['address_json'] && (h("bp-sdk-dynamic-input-redux-container", { class: "bp-sdk-address-group-address__json", labelledBy: this.labelledBy, shouldHideLabel: shouldHideQuestion(this.label, this.answerMap['address_json']), answer: this.answerMap['address_json'], hidden: true })), this.useAddressValidation && (h("bp-sdk-google-address-validation", { answerMap: this.answerMap, addressValidationId: this.addressValidationId }))));
    }
    static get is() { return "bp-sdk-address-group"; }
    static get originalStyleUrls() {
        return {
            "$": ["bp-sdk-address-group.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["bp-sdk-address-group.css"]
        };
    }
    static get properties() {
        return {
            "answers": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "IAnswer[]",
                    "resolved": "IAnswer[]",
                    "references": {
                        "IAnswer": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::IAnswer"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "group of answers"
                },
                "defaultValue": "[]"
            },
            "label": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "label"
                },
                "attribute": "label",
                "reflect": false
            },
            "labelledBy": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Labels that describe group"
                },
                "attribute": "labelled-by",
                "reflect": false
            },
            "disableAutoSave": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Disable automatically saving answers when typing.\nThis should only be used in specific advanced scenarios"
                },
                "attribute": "disable-auto-save",
                "reflect": false,
                "defaultValue": "false"
            },
            "useAddressValidation": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Render validation component"
                },
                "attribute": "use-address-validation",
                "reflect": false,
                "defaultValue": "false"
            },
            "addressValidationId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "AddressValidationId",
                    "resolved": "string",
                    "references": {
                        "AddressValidationId": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::AddressValidationId"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Answer pool ID if multiple address pool or group ID from the question set"
                },
                "attribute": "address-validation-id",
                "reflect": false
            }
        };
    }
    static get states() {
        return {
            "answerMap": {},
            "useExternal": {}
        };
    }
    static get events() {
        return [{
                "method": "saveAnswer",
                "name": "saveAnswer",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Passes information needed to update answer"
                },
                "complexType": {
                    "original": "IAnswerUpdatedEvent",
                    "resolved": "IAnswerUpdatedEvent",
                    "references": {
                        "IAnswerUpdatedEvent": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::IAnswerUpdatedEvent"
                        }
                    }
                }
            }, {
                "method": "addressMissingComponents",
                "name": "addressMissingComponents",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Passes missing address_components"
                },
                "complexType": {
                    "original": "{\n    missing_components: string[];\n  }",
                    "resolved": "{ missing_components: string[]; }",
                    "references": {}
                }
            }, {
                "method": "stageAddressValidationAnswerForUpdate",
                "name": "stageAddressValidationAnswerForUpdate",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": "Passes unsaved answer when `disableAutoSave` is true"
                },
                "complexType": {
                    "original": "IAnswerUpdatedEvent",
                    "resolved": "IAnswerUpdatedEvent",
                    "references": {
                        "IAnswerUpdatedEvent": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::IAnswerUpdatedEvent"
                        }
                    }
                }
            }];
    }
    static get watchers() {
        return [{
                "propName": "answers",
                "methodName": "onAnswersChange"
            }];
    }
    static get listeners() {
        return [{
                "name": "saveAnswer",
                "method": "onSaveAnswer",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "placesUpdate",
                "method": "onPlacesUpdate",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
