/*!
 * Built by ShiftSoftware
 * Copyright (c)
 */
import { Host, h } from "@stencil/core";
import partLookupWrapperSchema from "../../locales/partLookup/wrapper-type";
import { VehicleInfoLayout } from "../../features/vehicle-info-layout/index";
import { getLocaleLanguage, getSharedLocal, sharedLocalesSchema } from "../../features/multi-lingual/index";
import { smartInvokable } from "../../features/blazor-ref/index";
const componentTags = {
    deadStock: 'dead-stock-lookup',
    distributor: 'distributor-lookup',
    manufacturer: 'manufacturer-lookup',
};
export class PartLookup {
    constructor() {
        // #region Localization
        this.language = 'en';
        this.locale = sharedLocalesSchema.getDefault();
        // #endregion
        // ====== Wrapper Logic
        this.activeElement = '';
        this.mockUrl = '';
        this.isDev = false;
        this.wrapperErrorState = '';
        this.isError = false;
        this.header = '';
        this.isLoading = false;
        this.searchGeneration = 0;
        this.syncErrorAcrossComponents = (newErrorMessage) => {
            this.isError = true;
            this.errorKey = newErrorMessage;
            smartInvokable.bind(this)(this.errorCallback, newErrorMessage);
            Object.values(this.componentsList).forEach(element => {
                if (element)
                    element.setErrorMessage(newErrorMessage);
            });
        };
        this.loadingStateChangingMiddleware = (newState) => {
            this.isLoading = newState;
            smartInvokable.bind(this)(this.loadingStateChange, newState);
        };
        this.onMockDataSetMiddleware = (newMockData) => {
            smartInvokable.bind(this)(this.loadedMockDatas, newMockData);
        };
    }
    async componentWillLoad() {
        await this.changeLanguage(this.language);
    }
    async changeLanguage(newLanguage) {
        const localeResponses = await Promise.all([getLocaleLanguage(newLanguage, 'partLookup', partLookupWrapperSchema), getSharedLocal(newLanguage)]);
        this.locale = localeResponses[1];
    }
    async componentDidLoad() {
        const deadStockLookup = this.el.shadowRoot.getElementById(componentTags.deadStock);
        const distributerLookup = this.el.shadowRoot.getElementById(componentTags.distributor);
        const manufacturerLookup = this.el.shadowRoot.getElementById(componentTags.manufacturer);
        this.componentsList = {
            [componentTags.deadStock]: deadStockLookup,
            [componentTags.distributor]: distributerLookup,
            [componentTags.manufacturer]: manufacturerLookup,
        };
        Object.values(this.componentsList).forEach(element => {
            if (!element)
                return;
            element.loadedMockDatas = this.onMockDataSetMiddleware;
            element.errorCallback = this.syncErrorAcrossComponents;
            element.loadingStateChange = this.loadingStateChangingMiddleware;
            element.loadedResponse = newResponse => this.handleLoadData(newResponse, element);
        });
    }
    async handleLoadData(newResponse, activeElement) {
        const generation = this.searchGeneration;
        this.isError = false;
        this.header = (newResponse === null || newResponse === void 0 ? void 0 : newResponse.partNumber) || '';
        smartInvokable.bind(this)(this.loadedResponse, newResponse);
        // Skip distributing to non-active components if a new search has started
        if (generation !== this.searchGeneration)
            return;
        Object.values(this.componentsList).forEach(element => {
            // @ts-ignore
            if (element !== null && element !== activeElement && newResponse)
                element.fetchData(newResponse);
        });
    }
    async errorListener(newState) {
        smartInvokable.bind(this)(this.errorCallback, newState);
    }
    async setBlazorRef(newBlazorRef) {
        this.blazorRef = newBlazorRef;
    }
    async fetchData(partNumber, quantity = '') {
        const activeElement = this.componentsList[this.activeElement] || null;
        this.wrapperErrorState = '';
        if (!activeElement)
            return;
        if (partNumber == '')
            return (this.wrapperErrorState = this.locale.errors.partNumberRequired);
        this.searchGeneration++;
        const searchingText = quantity.trim() || quantity.trim() === '0' ? `${partNumber.trim()}/${quantity.trim()}` : partNumber.trim();
        activeElement.fetchData(searchingText);
    }
    async getMockData() {
        const activeElement = this.componentsList[this.activeElement] || null;
        const mockData = await activeElement.getMockData();
        return mockData;
    }
    // #endregion
    render() {
        const props = {
            [componentTags.deadStock]: {},
            [componentTags.distributor]: {},
            [componentTags.manufacturer]: {},
        };
        try {
            if (this.childrenProps) {
                let parsedProps = {};
                if (typeof this.childrenProps === 'string')
                    parsedProps = JSON.parse(this.childrenProps);
                else if (typeof this.childrenProps === 'object')
                    parsedProps = this.childrenProps;
                Object.keys(props).forEach(key => {
                    if (typeof parsedProps[key] === 'object')
                        props[key] = parsedProps[key];
                });
            }
        }
        catch (error) {
            console.error(error);
        }
        if (!Object.values(componentTags).includes(this.activeElement))
            return h("div", { class: "w-full h-[200px] text-[26px] text-red-600 flex items-center justify-center" }, "Invalid tag");
        const componentList = {
            'dead-stock-lookup': (h("dead-stock-lookup", Object.assign({ coreOnly: true, isDev: this.isDev, "mock-url": this.mockUrl, language: this.language, endpoint: this.endpoint, id: componentTags.deadStock }, props[componentTags.deadStock]))),
            'distributor-lookup': (h("distributor-lookup", Object.assign({ coreOnly: true, isDev: this.isDev, "mock-url": this.mockUrl, language: this.language, endpoint: this.endpoint, id: componentTags.distributor }, props[componentTags.distributor]))),
            'manufacturer-lookup': (h("manufacturer-lookup", Object.assign({ coreOnly: true, isDev: this.isDev, "mock-url": this.mockUrl, language: this.language, endpoint: this.endpoint, id: componentTags.manufacturer }, props[componentTags.manufacturer]))),
        };
        return (h(Host, { class: "part-lookup", translate: "no" }, h(VehicleInfoLayout, { isError: this.isError, header: this.header, isLoading: this.isLoading, direction: this.locale.direction, errorMessage: this.locale.errors[this.errorKey] || this.locale.errors.wildCard }, h("shift-tab-content", { components: componentList, activeComponent: this.activeElement }))));
    }
    static get is() { return "part-lookup"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["part-lookup.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["part-lookup.css"]
        };
    }
    static get properties() {
        return {
            "language": {
                "type": "string",
                "attribute": "language",
                "mutable": false,
                "complexType": {
                    "original": "LanguageKeys",
                    "resolved": "\"ar\" | \"en\" | \"ku\" | \"ru\"",
                    "references": {
                        "LanguageKeys": {
                            "location": "import",
                            "path": "~features/multi-lingual",
                            "id": "src/features/multi-lingual/index.ts::LanguageKeys"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "'en'"
            },
            "activeElement": {
                "type": "string",
                "attribute": "active-element",
                "mutable": false,
                "complexType": {
                    "original": "ActiveElement",
                    "resolved": "\"\" | \"dead-stock-lookup\" | \"distributor-lookup\" | \"manufacturer-lookup\"",
                    "references": {
                        "ActiveElement": {
                            "location": "local",
                            "path": "/home/vsts/work/1/s/ADP.WebComponents/adp-web-components/src/components/part-lookup/part-lookup.tsx",
                            "id": "src/components/part-lookup/part-lookup.tsx::ActiveElement"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            },
            "mockUrl": {
                "type": "string",
                "attribute": "mock-url",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "''"
            },
            "endpoint": {
                "type": "string",
                "attribute": "endpoint",
                "mutable": false,
                "complexType": {
                    "original": "Endpoint",
                    "resolved": "string | { url: string; body?: object; headers?: object; method?: string; query?: QueryString; }",
                    "references": {
                        "Endpoint": {
                            "location": "import",
                            "path": "~lib/fetch-from",
                            "id": "src/global/lib/fetch-from.ts::Endpoint"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "isDev": {
                "type": "boolean",
                "attribute": "is-dev",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false,
                "defaultValue": "false"
            },
            "childrenProps": {
                "type": "string",
                "attribute": "children-props",
                "mutable": false,
                "complexType": {
                    "original": "string | Object",
                    "resolved": "Object | string",
                    "references": {
                        "Object": {
                            "location": "global",
                            "id": "global::Object"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "loadedMockDatas": {
                "type": "string",
                "attribute": "loaded-mock-datas",
                "mutable": true,
                "complexType": {
                    "original": "BlazorInvokableFunction<(response: any) => void>",
                    "resolved": "((response: any) => void) | string",
                    "references": {
                        "BlazorInvokableFunction": {
                            "location": "import",
                            "path": "~features/blazor-ref",
                            "id": "src/features/blazor-ref/index.ts::BlazorInvokableFunction"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "errorCallback": {
                "type": "string",
                "attribute": "error-callback",
                "mutable": true,
                "complexType": {
                    "original": "BlazorInvokableFunction<(errorMessage: ErrorKeys) => void>",
                    "resolved": "((errorMessage: OptionalKeys<{ noBaseUrl: string; invalidVin: string; vinNumberRequired: string; partNumberRequired: string; wrongResponseFormat: string; noPartsFound: string; noServiceAvailable: string; wrongFormStructure: string; wildCard: string; requestFailedPleaseTryAgainLater: string; }>) => void) | string",
                    "references": {
                        "BlazorInvokableFunction": {
                            "location": "import",
                            "path": "~features/blazor-ref",
                            "id": "src/features/blazor-ref/index.ts::BlazorInvokableFunction"
                        },
                        "ErrorKeys": {
                            "location": "import",
                            "path": "~features/multi-lingual",
                            "id": "src/features/multi-lingual/index.ts::ErrorKeys"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "loadingStateChange": {
                "type": "string",
                "attribute": "loading-state-change",
                "mutable": true,
                "complexType": {
                    "original": "BlazorInvokableFunction<(isLoading: boolean) => void>",
                    "resolved": "((isLoading: boolean) => void) | string",
                    "references": {
                        "BlazorInvokableFunction": {
                            "location": "import",
                            "path": "~features/blazor-ref",
                            "id": "src/features/blazor-ref/index.ts::BlazorInvokableFunction"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            },
            "loadedResponse": {
                "type": "string",
                "attribute": "loaded-response",
                "mutable": true,
                "complexType": {
                    "original": "BlazorInvokableFunction<(response: PartLookupDTO) => void>",
                    "resolved": "((response: PartLookupDTO) => void) | string",
                    "references": {
                        "BlazorInvokableFunction": {
                            "location": "import",
                            "path": "~features/blazor-ref",
                            "id": "src/features/blazor-ref/index.ts::BlazorInvokableFunction"
                        },
                        "PartLookupDTO": {
                            "location": "import",
                            "path": "~types/generated/part/part-lookup-dto",
                            "id": "src/global/types/generated/part/part-lookup-dto.ts::PartLookupDTO"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "reflect": false
            }
        };
    }
    static get states() {
        return {
            "locale": {},
            "errorKey": {},
            "wrapperErrorState": {},
            "isError": {},
            "header": {},
            "isLoading": {},
            "blazorRef": {}
        };
    }
    static get methods() {
        return {
            "handleLoadData": {
                "complexType": {
                    "signature": "(newResponse: PartLookupDTO, activeElement: any) => Promise<void>",
                    "parameters": [{
                            "name": "newResponse",
                            "type": "{ partNumber: string; partDescription: string; localDescription: string; productGroup: string; pnc: string; binType: string; showManufacturerPartLookup: boolean; distributorPurchasePrice?: number; length?: number; width?: number; height?: number; netWeight?: number; grossWeight?: number; cubicMeasure?: number; hsCode: string; origin: string; supersededTo: string[]; supersededFrom: string[]; stockParts: StockPartDTO[]; prices: PartPriceDTO[]; hsCodes: HSCodeDTO[]; deadStock: DeadStockDTO[]; logId?: string; }",
                            "docs": ""
                        }, {
                            "name": "activeElement",
                            "type": "any",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "PartLookupDTO": {
                            "location": "import",
                            "path": "~types/generated/part/part-lookup-dto",
                            "id": "src/global/types/generated/part/part-lookup-dto.ts::PartLookupDTO"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "setBlazorRef": {
                "complexType": {
                    "signature": "(newBlazorRef: DotNetObjectReference) => Promise<void>",
                    "parameters": [{
                            "name": "newBlazorRef",
                            "type": "{ invokeMethodAsync: (methodName: string, ...args: any[]) => Promise<any>; }",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        },
                        "DotNetObjectReference": {
                            "location": "import",
                            "path": "~features/blazor-ref",
                            "id": "src/features/blazor-ref/index.ts::DotNetObjectReference"
                        }
                    },
                    "return": "Promise<void>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "fetchData": {
                "complexType": {
                    "signature": "(partNumber: string, quantity?: string) => Promise<string>",
                    "parameters": [{
                            "name": "partNumber",
                            "type": "string",
                            "docs": ""
                        }, {
                            "name": "quantity",
                            "type": "string",
                            "docs": ""
                        }],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<string>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            },
            "getMockData": {
                "complexType": {
                    "signature": "() => Promise<any>",
                    "parameters": [],
                    "references": {
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    },
                    "return": "Promise<any>"
                },
                "docs": {
                    "text": "",
                    "tags": []
                }
            }
        };
    }
    static get elementRef() { return "el"; }
    static get watchers() {
        return [{
                "propName": "language",
                "methodName": "changeLanguage"
            }, {
                "propName": "wrapperErrorState",
                "methodName": "errorListener"
            }];
    }
}
