import { h, Host } from "@stencil/core";
import { state as headerState } from "./pn-marketweb-siteheader-store";
import { arrow_right } from "pn-design-assets/pn-assets/icons.js";
export class PnMarketwebSiteheaderLoginProfileselection {
    constructor() {
        this.loginDialog = null;
        this.endpoint = '';
        this.loggedin = false;
        this.idNamespace = '';
        this.heading = null;
        this.i18n = {
            searchlabel: '',
            searchplaceholder: '',
            searchbuttontext: '',
            menuHomeButton: '',
            menuGoBackButton: '',
            mainMenuButton: '',
            menuStartButton: '',
            profileSelectionFlyoutHeading: '',
        };
        this.user = null;
        this.logoutLink = null;
        this.userName = null;
        this.userEmail = '';
        this.currentProfile = null;
        this.profileoptions = [];
    }
    hostElement;
    componentWillLoad() {
        if (this.heading === null && this.i18n?.profileSelectionFlyoutHeading) {
            this.heading = this.i18n.profileSelectionFlyoutHeading;
        }
        this.init();
    }
    init() {
        this.updateUserInfo();
        this.adjustLoginLinks();
        this.fetchProfiles();
    }
    async fetchProfiles() {
        if (!this.loggedin || this.profileoptions.length > 0) {
            return;
        }
        let apiUrl = `${this.endpoint}${this.endpoint.lastIndexOf('/') > -1 && this.endpoint.lastIndexOf('/') === this.endpoint.length - 1 ? '' : '/'}api/user/parentorganizations`;
        const req = await fetch(apiUrl);
        const reqdata = await req.json();
        const fallbackData = {
            loggedin: true,
            organizations: [
                {
                    name: 'Forsheda Livs AB',
                    customerNumber: '5564513603',
                    id: 'dbba867d-1dff-3dbb-b420-c57b4b828b73',
                    selected: true,
                    profiles: [
                        {
                            name: 'Forsheda Livs AB',
                            customerNumber: '20685482',
                            id: 'f757ba28-9a73-15a2-f128-4b394d970f3f',
                            ssid: '',
                            selected: false,
                            customerGroup: 'Business',
                        },
                        {
                            name: 'ICA MAXI KUNGSBACKA',
                            customerNumber: '20831191',
                            id: '5aea41df-32b0-3f7e-2946-78598360177d',
                            ssid: '259686',
                            selected: true,
                            customerGroup: 'Agent',
                        },
                    ],
                },
                {
                    name: 'Hem Livs i Kungsbacka AB',
                    customerNumber: '5565271250',
                    id: '97ca363c-40ef-cca9-7a3c-9e7f025567c2',
                    selected: false,
                    profiles: [
                        {
                            name: 'ICA KVANTUM KUNGSBACKA',
                            customerNumber: '20831193',
                            id: 'fbd61ffd-41c6-2206-b88e-cfef91e1dc39',
                            ssid: '259691',
                            selected: false,
                            customerGroup: 'Agent',
                        },
                    ],
                },
                {
                    name: 'ICA SUPERMARKET TORGET',
                    customerNumber: '5568902679',
                    id: '7cb76a94-e1a5-5f57-58fd-bc563851b28e',
                    selected: false,
                    profiles: [
                        {
                            name: 'ICA SUPERMARKET TORGET',
                            customerNumber: '20831212',
                            id: '3a2db017-b68f-6fa0-fe70-542c08cd97ce',
                            ssid: '',
                            selected: false,
                            customerGroup: 'Agent',
                        },
                    ],
                },
            ],
        };
        const data = window.location.href.indexOf('localhost:6008') !== -1 ? fallbackData : reqdata;
        if (!data || !data.organizations || !data.organizations.length) {
            this.heading = ""; //this is to not get "logged in as" text when its private account
            return;
        }
        data.organizations.forEach(org => {
            if (org.selected === true && org.profiles) {
                const selectedProfile = org.profiles.filter(x => x.selected === true);
                if (selectedProfile && selectedProfile[0] && selectedProfile[0].customerGroup.toLocaleLowerCase() === 'agent' && selectedProfile[0].ssid) {
                    org.customerNumber = selectedProfile[0].ssid;
                }
            }
            else {
                if (org.customerNumber.length === 10 && org.customerNumber.substring(0, 2) === '55') {
                    org.customerNumber = org.customerNumber.substring(0, 6) + '-' + org.customerNumber.substring(6);
                }
                this.profileoptions.push(org);
            }
        });
        let currentProfileObj = data.organizations.filter(x => x.selected === true)[0];
        const userProfileOption = {
            name: this.userName,
            customerNumber: '',
            id: '',
            selected: !currentProfileObj,
            profiles: [],
        };
        if (!currentProfileObj) {
            currentProfileObj = userProfileOption;
        }
        if (currentProfileObj && currentProfileObj.name) {
            this.currentProfile = currentProfileObj;
        }
        this.profileoptions.push(userProfileOption);
    }
    adjustLoginLinks() {
        const adjustLink = (link, i) => {
            if (!link.isLogoutLink) {
                link.isLogoutLink = link.pageLink.indexOf('location.href') !== -1 && link.pageLink.indexOf('logout') !== -1;
            }
            if (link.isLogoutLink) {
                link.href = headerState.loginManager.getLogoutUrl(link.href);
            }
            if (i === 0 && !link.href) {
                link.href = headerState.loginManager.getLoginUrl();
                link.linkType = 'primary';
            }
            if (link.primaryLinkApperance && !link.linkType) {
                link.linkType = 'primary';
            }
        };
        if (this.loginDialog?.loggedInLinks) {
            this.loginDialog?.loggedInLinks.forEach(adjustLink);
        }
        this.logoutLink = this.loginDialog?.loggedInLinks.filter(x => x.isLogoutLink)[0] ?? null;
    }
    updateUserInfo() {
        const userInfo = headerState.loginManager.getUserInfo();
        this.user = userInfo;
        if (!userInfo) {
            return;
        }
        if (userInfo && userInfo.email) {
            this.userEmail = userInfo.email;
        }
        if (userInfo && userInfo.given_name) {
            this.userName = userInfo.given_name + (userInfo?.family_name ? ` ${userInfo?.family_name}` : '');
        }
        if (userInfo && userInfo.given_name) {
            this.userName = userInfo.given_name;
            return;
        }
        if (userInfo && userInfo.family_name) {
            this.userName = userInfo.family_name;
            return;
        }
        if (userInfo && userInfo.username) {
            this.userName = userInfo.username;
            return;
        }
    }
    filterLogoutLink(loggedInLinks) {
        return loggedInLinks.filter((link) => !link.isLogoutLink);
    }
    render() {
        if (!this.loginDialog) {
            return;
        }
        let hostElementAttribute = {};
        return (h(Host, { ...hostElementAttribute }, this.heading ? h("strong", { class: "pn-marketweb-siteheader-login-profileselection-heading" }, this.heading) : null, this.currentProfile !== null && this.currentProfile.name ? (h("div", { class: "pn-marketweb-siteheader-login-profileselection-currentprofile" }, h("div", { class: "pn-marketweb-siteheader-login-profileselection-currentprofile-name" }, this.currentProfile.name), h("div", { class: "pn-marketweb-siteheader-login-profileselection-currentprofile-description" }, this.currentProfile.customerNumber ? this.currentProfile.customerNumber : this.userEmail))) : null, h("pn-marketweb-siteheader-login-linklist", { links: this.filterLogoutLink(this.loginDialog.loggedInLinks), idNamespace: this.idNamespace }), h("div", { class: "pn-marketweb-siteheader-login-profileselection-divider" }), this.profileoptions
            .filter(x => x.selected !== true)
            .map(organization => {
            let customerNumber = organization.profiles.length > 0 ? organization.profiles[0].customerNumber : organization.customerNumber;
            return (h("div", { class: "pn-marketweb-siteheader-login-profileselection-profileoption" }, h("a", { href: `${this.endpoint}/api/user/setprofile?customernumber=${customerNumber}&returnUrl=${encodeURIComponent(window.location.href)}`, class: "pn-marketweb-siteheader-login-profileselection-profileoption-link" }, h("div", { class: "pn-marketweb-siteheader-login-profileselection-profileoption-content" }, h("div", { class: "pn-marketweb-siteheader-login-profileselection-profileoption-name" }, organization.name), h("div", { class: "pn-marketweb-siteheader-login-profileselection-profileoption-description" }, organization.customerNumber ? organization.customerNumber : this.userEmail)), h("pn-icon", { icon: arrow_right, small: "false", color: "blue700" }))));
        }), this.logoutLink ? (h("div", { class: "pn-marketweb-siteheader-login-profileselection-logout" }, h("a", { href: this.logoutLink.href, rel: "nofollower noopener", id: "pn-marketweb-header-logoutlink", onClick: () => headerState.loginManager.clearUserData(), class: "pn-marketweb-siteheader-login-profileselection-logout-link" }, this.logoutLink.linkText))) : null));
    }
    static get is() { return "pn-marketweb-siteheader-login-profileselection"; }
    static get originalStyleUrls() {
        return {
            "$": ["pn-marketweb-siteheader-login-profileselection.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["pn-marketweb-siteheader-login-profileselection.css"]
        };
    }
    static get properties() {
        return {
            "loginDialog": {
                "type": "unknown",
                "mutable": true,
                "complexType": {
                    "original": "LoginDialog",
                    "resolved": "LoginDialog",
                    "references": {
                        "LoginDialog": {
                            "location": "import",
                            "path": "./pn-marketweb-siteheader-types",
                            "id": "src/components/layout-components/pn-marketweb-siteheader/pn-marketweb-siteheader-types.ts::LoginDialog"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "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": "''"
            },
            "loggedin": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "loggedin",
                "reflect": false,
                "defaultValue": "false"
            },
            "idNamespace": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "id-namespace",
                "reflect": false,
                "defaultValue": "''"
            },
            "heading": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "heading",
                "reflect": false,
                "defaultValue": "null"
            },
            "i18n": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "SiteHeaderI18N",
                    "resolved": "SiteHeaderI18N",
                    "references": {
                        "SiteHeaderI18N": {
                            "location": "import",
                            "path": "./pn-marketweb-siteheader-types",
                            "id": "src/components/layout-components/pn-marketweb-siteheader/pn-marketweb-siteheader-types.ts::SiteHeaderI18N"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "defaultValue": "{\n    searchlabel: '',\n    searchplaceholder: '',\n    searchbuttontext: '',\n    menuHomeButton: '',\n    menuGoBackButton: '',\n    mainMenuButton: '',\n    menuStartButton: '',\n    profileSelectionFlyoutHeading: '',\n  } as SiteHeaderI18N"
            },
            "currentProfile": {
                "type": "unknown",
                "mutable": true,
                "complexType": {
                    "original": "ProfileSelectorCustomerItem",
                    "resolved": "ProfileSelectorCustomerItem",
                    "references": {
                        "ProfileSelectorCustomerItem": {
                            "location": "import",
                            "path": "./pn-marketweb-siteheader-types",
                            "id": "src/components/layout-components/pn-marketweb-siteheader/pn-marketweb-siteheader-types.ts::ProfileSelectorCustomerItem"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "defaultValue": "null"
            },
            "profileoptions": {
                "type": "unknown",
                "mutable": true,
                "complexType": {
                    "original": "ProfileSelectorOrganization[]",
                    "resolved": "ProfileSelectorOrganization[]",
                    "references": {
                        "ProfileSelectorOrganization": {
                            "location": "import",
                            "path": "./pn-marketweb-siteheader-types",
                            "id": "src/components/layout-components/pn-marketweb-siteheader/pn-marketweb-siteheader-types.ts::ProfileSelectorOrganization"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "defaultValue": "[]"
            }
        };
    }
    static get states() {
        return {
            "user": {},
            "logoutLink": {},
            "userName": {},
            "userEmail": {}
        };
    }
    static get elementRef() { return "hostElement"; }
}
//# sourceMappingURL=pn-marketweb-siteheader-login-profileselection.js.map
