import { getVehicleOptionsMakes, getVehicleOptionsSelection } from "@boldpenguin/sdk-redux";
import { YmmcUpdateType, } from "@boldpenguin/sdk-types";
import { hasRequiredError, hasValueChanged } from "@boldpenguin/sdk-utility";
import { h } from "@stencil/core";
import store from "../../services/redux-store.service";
export class BpSdkVehicleMakesContainer {
    constructor() {
        this.handleSubscriptions = () => {
            this.storeUnsubscribe && this.storeUnsubscribe();
            this.storeUnsubscribe = store.mapStateToProps(this, this.mapStateToProps);
        };
        this.mapStateToProps = (state) => {
            return {
                makeOptions: getVehicleOptionsMakes(state, this.questionGroupId),
                selectedVehicle: getVehicleOptionsSelection(state, this.questionGroupId),
            };
        };
        this.onFocusOut = () => {
            this.touched = true;
            this.updateErrors(this.pristine, true, this.value);
        };
        this.answerId = undefined;
        this.code = undefined;
        this.makeOptions = {};
        this.selectedVehicle = {};
        this.questionGroupId = undefined;
        this.isVehicleTrailer = false;
        this.answeredBySource = '';
        this.choices = [];
        this.filter = undefined;
        this.filteredChoices = [];
        this.useExternal = false;
        this.touched = false;
        this.pristine = true;
        this.value = undefined;
        this.errors = [];
    }
    resetState() {
        this.touched = false;
        this.pristine = true;
        this.value = undefined;
        this.errors = [];
    }
    connectedCallback() {
        this.resetState();
        this.handleSubscriptions();
    }
    componentWillLoad() {
        this.useExternal = !!customElements.get('bp-sdk-external-vehicle-makes-container');
        customElements.whenDefined('bp-sdk-external-vehicle-makes-container').then(() => {
            this.useExternal = true;
        });
        this.onQuestionGroupIdChange();
    }
    onQuestionGroupIdChange() {
        this.handleSubscriptions();
    }
    onMakesChange(makes) {
        if (makes) {
            this.choices = this.convertMakesToChoices(makes);
            this.updateValue(makes, this.selectedVehicle);
        }
        else {
            this.updateValue(undefined, undefined);
        }
    }
    onVehicleSelectionChange(selection) {
        if (!(selection === null || selection === void 0 ? void 0 : selection.makeId)) {
            this.touched = false;
            this.pristine = true;
        }
        this.updateValue(this.makeOptions, selection);
    }
    updateValue(makes, selection) {
        this.value = !!(makes && (selection === null || selection === void 0 ? void 0 : selection.makeId)) ? makes[selection.makeId] : undefined;
    }
    onUseExternalChange(useExternal) {
        if (!useExternal) {
            this.unloadFocusEvents();
        }
    }
    loadFocusEvents() {
        if (!this.useExternal) {
            this.el.addEventListener('focusout', this.onFocusOut);
        }
    }
    unloadFocusEvents() {
        this.el.removeEventListener('focusout', this.onFocusOut);
    }
    componentDidLoad() {
        this.loadFocusEvents();
    }
    disconnectedCallback() {
        this.unloadFocusEvents();
        this.storeUnsubscribe && this.storeUnsubscribe();
    }
    onFilterUpdate({ detail }) {
        var _a;
        this.filter = (_a = detail === null || detail === void 0 ? void 0 : detail.value) !== null && _a !== void 0 ? _a : '';
    }
    onFilterChange(filter) {
        this.updateChoices(this.choices, filter);
    }
    onChoicesChange(choices) {
        this.updateChoices(choices, this.filter);
    }
    updateChoices(choices, filter = '') {
        const regex = new RegExp(`.*${filter}.*`, 'gi');
        this.filteredChoices = choices.filter((choice) => !!choice.value.match(regex));
    }
    onValueUpdate(evt) {
        var _a, _b;
        if (this.useExternal) {
            return;
        }
        this.pristine = false;
        const value = ((_a = evt.detail) !== null && _a !== void 0 ? _a : [])[0];
        if (hasValueChanged(value, this.value) && (this.errors.length === 0 || !!value)) {
            this.value = value;
            this.ymmcUpdate.emit({
                value,
                type: YmmcUpdateType.Make,
                displayValue: (_b = this.makeOptions[value]) !== null && _b !== void 0 ? _b : value,
                freeform: this.makeOptions[value] == null,
            });
        }
    }
    onValueChange(value) {
        this.updateErrors(false, this.touched, value);
    }
    updateErrors(pristine, touched, value) {
        this.errors = hasRequiredError(pristine, touched, value) ? ['required'] : [];
    }
    onMakeDirty() {
        this.touched = true;
        this.pristine = false;
        this.updateErrors(false, this.touched, this.value);
    }
    render() {
        return [this.useExternal && this.renderExternal(), !this.useExternal && this.renderInternal()];
    }
    renderExternal() {
        return (h("bp-sdk-external-vehicle-makes-container", { answerId: this.answerId, code: this.code, isVehicleTrailer: this.isVehicleTrailer, makeOptions: this.makeOptions, questionGroupId: this.questionGroupId, selectedVehicle: this.selectedVehicle }));
    }
    convertMakesToChoices(makes) {
        const choices = [];
        for (const makeId of Object.keys(makes)) {
            choices.push({ id: makeId, value: makes[makeId] });
        }
        choices.sort((a, b) => a.value.localeCompare(b.value));
        return choices;
    }
    renderInternal() {
        var _a;
        return (this.choices.length > 0 && (h("bp-sdk-vehicle-makes", { answerId: this.answerId, code: this.code, errors: this.errors, isVehicleTrailer: this.isVehicleTrailer, label: "Enter vehicle make", makes: this.filteredChoices, pristine: this.pristine, selectedMakeId: (_a = this.selectedVehicle) === null || _a === void 0 ? void 0 : _a.makeId, touched: this.touched, answeredBySource: this.answeredBySource })));
    }
    static get is() { return "bp-sdk-vehicle-makes-container"; }
    static get originalStyleUrls() {
        return {
            "$": ["./bp-sdk-vehicle-makes-container.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["bp-sdk-vehicle-makes-container.css"]
        };
    }
    static get properties() {
        return {
            "answerId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The id of the answer associated with this field"
                },
                "attribute": "answer-id",
                "reflect": false
            },
            "code": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The question code associated with this field"
                },
                "attribute": "code",
                "reflect": false
            },
            "makeOptions": {
                "type": "unknown",
                "mutable": true,
                "complexType": {
                    "original": "IVehicleMakeOptions",
                    "resolved": "IVehicleMakeOptions",
                    "references": {
                        "IVehicleMakeOptions": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::IVehicleMakeOptions"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Vehicle options injected by redux"
                },
                "defaultValue": "{}"
            },
            "selectedVehicle": {
                "type": "unknown",
                "mutable": true,
                "complexType": {
                    "original": "IVehicleSelection",
                    "resolved": "IVehicleSelection",
                    "references": {
                        "IVehicleSelection": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::IVehicleSelection"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Current vehicle selection injected by redux"
                },
                "defaultValue": "{}"
            },
            "questionGroupId": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Vehicle question group ID"
                },
                "attribute": "question-group-id",
                "reflect": false
            },
            "isVehicleTrailer": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Is vehicle a trailer"
                },
                "attribute": "is-vehicle-trailer",
                "reflect": false,
                "defaultValue": "false"
            },
            "answeredBySource": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "The source a question was answered by, if not answered directly"
                },
                "attribute": "answered-by-source",
                "reflect": false,
                "defaultValue": "''"
            }
        };
    }
    static get states() {
        return {
            "choices": {},
            "filter": {},
            "filteredChoices": {},
            "useExternal": {},
            "touched": {},
            "pristine": {},
            "value": {},
            "errors": {}
        };
    }
    static get events() {
        return [{
                "method": "ymmcUpdate",
                "name": "ymmcUpdate",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "IYearMakeModelConfigurationUpdate",
                    "resolved": "IYearMakeModelConfigurationUpdate",
                    "references": {
                        "IYearMakeModelConfigurationUpdate": {
                            "location": "import",
                            "path": "@boldpenguin/sdk-types",
                            "id": "../sdk-types/dist/types.d.ts::IYearMakeModelConfigurationUpdate"
                        }
                    }
                }
            }];
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "questionGroupId",
                "methodName": "onQuestionGroupIdChange"
            }, {
                "propName": "makeOptions",
                "methodName": "onMakesChange"
            }, {
                "propName": "selectedVehicle",
                "methodName": "onVehicleSelectionChange"
            }, {
                "propName": "useExternal",
                "methodName": "onUseExternalChange"
            }, {
                "propName": "filter",
                "methodName": "onFilterChange"
            }, {
                "propName": "choices",
                "methodName": "onChoicesChange"
            }, {
                "propName": "value",
                "methodName": "onValueChange"
            }];
    }
    static get listeners() {
        return [{
                "name": "filterUpdate",
                "method": "onFilterUpdate",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "valueUpdate",
                "method": "onValueUpdate",
                "target": undefined,
                "capture": false,
                "passive": false
            }, {
                "name": "makeDirty",
                "method": "onMakeDirty",
                "target": undefined,
                "capture": false,
                "passive": false
            }];
    }
}
