import { h, Host } from "@stencil/core";
import { FetchHelper } from "../../../globals/FetchHelper";
import { MarketWebContextService } from "../../../globals/MarketWebContextService";
import { getSocialMediaIconsByType } from "./socialMediaIcons";
import { translations } from "./translations";
import { HeadingTag } from "../../../globals/HeadingTag";
export class PnMarketwebSiteheader {
    constructor() {
        this.market = 'se';
        this.language = 'sv';
        this.environment = null;
        this.endpoint = null;
        this.siteDomainInUrls = false;
        this.cache = false;
        this.theme = 'default';
        this.backgroundcolor = 'darkestblue';
        this.showSwan = false;
        this.headingLevel = "h2";
        this.siteDefinition = undefined;
        this.footerContent = undefined;
        this.i18n = undefined;
        this.gotData = false;
        this.fetchingData = false;
    }
    hostElement;
    fetchHelper = new FetchHelper('sitefooter');
    endpointPath = '/api/footer/footer';
    componentWillLoad() {
        this.setInitialValues().then(() => {
            this.init();
        });
    }
    async setInitialValues(href = window.location.href) {
        const marketWebContextService = new MarketWebContextService(href);
        if (!this.market) {
            const resolvedMarket = await marketWebContextService.getMarket();
            this.market = resolvedMarket;
        }
        if (!this.language) {
            const resolvedMarket = await marketWebContextService.getLanguage();
            this.language = resolvedMarket;
        }
        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 = '';
        }
    }
    async init() {
        this.setTranslations();
        await this.fetchData();
    }
    setTranslations() {
        if (this.language && translations[this.language]) {
            this.i18n = translations[this.language];
        }
    }
    onLanguageChange() {
        this.setTranslations();
        this.fetchData();
    }
    onMarketChange() {
        this.fetchData();
    }
    setFetchUrl(endpointBase) {
        switch (this.theme) {
            case 'dotcom':
                return `${endpointBase}${this.endpointPath}?market=${this.market}&language=${this.language}&breakOutSocialMedia=true&extendColumns=true`;
            default:
                return `${endpointBase}${this.endpointPath}?market=${this.market}&language=${this.language}`;
        }
    }
    async fetchData() {
        if (this.endpoint === null || !this.market || !this.language) {
            // console.warn(`One or more values where not specified.\nEndpoint: ${this.endpoint}\nMarket: ${this.market}\nLanguage: ${this.language}`)
            return;
        }
        this.fetchingData = true;
        const endpointBase = this.endpoint.lastIndexOf('/') === this.endpoint.length - 1 ? this.endpoint.substring(0, this.endpoint.length - 1) : this.endpoint;
        const fetchUrl = this.setFetchUrl(endpointBase);
        const data = (await this.fetchHelper.fetchJson(fetchUrl, {
            mode: 'cors',
        }, this.cache, this.onFetchRefreshed.bind(this)));
        await this.setStateFromData(data);
    }
    onFetchRefreshed(data) {
        this.setStateFromData(data);
    }
    setStateFromData(data) {
        if (typeof data !== 'object') {
            console.warn('Data was not valid', data);
        }
        this.siteDefinition = data.sitedefinition;
        this.footerContent = data.footer;
        if (this.siteDomainInUrls) {
            this.adjustLinks();
        }
        this.gotData = true;
        this.fetchingData = true;
    }
    adjustLinks() {
        this.footerContent.bottomLinks.forEach(link => {
            link.linkHref = this.adjustHref(link.linkHref);
        });
        this.footerContent.columns.forEach(col => {
            col.links.forEach(link => {
                link.linkHref = this.adjustHref(link.linkHref);
            });
        });
    }
    adjustHref(href) {
        if (!href || href.indexOf('http') === 0 || this.siteDomainInUrls) {
            return href;
        }
        const domainUrl = this.siteDefinition.url.lastIndexOf('/') === this.siteDefinition.url.length - 1
            ? this.siteDefinition.url.substring(0, this.siteDefinition.url.length - 1)
            : this.siteDefinition.url;
        href = domainUrl + href;
        return href;
    }
    uniqueId(text) {
        return 'footer-' + text.replace(/[^A-Za-z0-9.\\\/]/gim, '');
    }
    renderCols() {
        if (this.gotData && this.footerContent?.columns) {
            return this.footerContent.columns.map(column => {
                return (h("pn-site-footer-col", { theme: this.theme }, column.firstLinkAsHeader && column.links && column.links[0] ? (h("a", { href: column.links[0].linkHref, target: column.links[0].openInNewWindow ? '_blank' : null, rel: column.links[0].openInNewWindow ? 'noopener nofollower noreferrer' : null, title: column.links[0].linkText, id: this.uniqueId(column.links[0].linkText) }, h(HeadingTag, { level: this.headingLevel, cssClass: `${"pn-" + this.headingLevel}` }, column.links[0].linkText))) : (h(HeadingTag, { level: this.headingLevel, cssClass: `${"pn-" + this.headingLevel}` }, column.heading)), column.links && (!column.body || this.theme === 'tpl') ? (h("ul", { ...(column.links && column.links[0] && column.links[0].linkType && { class: 'social-media' }) }, column.links.map((link, i) => {
                    if (!link.linkHref || (column.firstLinkAsHeader && i == 0)) {
                        return false;
                    }
                    let linkText = link.linkText;
                    if (link.linkType) {
                        linkText = getSocialMediaIconsByType(link.linkType);
                    }
                    let linkId = this.uniqueId(linkText);
                    return (h("li", null, h("a", { href: link.linkHref, ...(link.openInNewWindow && { target: '_blank' }), title: link.linkText, innerHTML: linkText, id: linkId }, this.theme === 'tpl' ? h("span", { class: "footer-tpl-links" }, link.linkText) : null)));
                }))) : null, column.body ? h("div", { innerHTML: column.body }) : null, h("slot", { name: "bottomsocialmediadesktop" }), h("slot", { name: "bottomsocialmediamobile" })));
            });
        }
        else {
            return null;
        }
    }
    renderBottomLinks() {
        return this.footerContent.bottomLinks.map(link => {
            if (!link.linkHref) {
                return h("li", null, link.linkText);
            }
            let linkId = this.uniqueId(link.linkText);
            return (h("li", null, h("a", { href: link.linkHref, ...(link.openInNewWindow && { target: '_blank' }), title: link.linkText, id: linkId }, link.linkText)));
        });
    }
    renderDefaultFooter() {
        return (h(Host, { language: this.language, market: this.market, environment: this.environment }, h("pn-site-footer", { url: this.siteDefinition?.url ?? '' }, h("slot", { name: "logo" }), this.renderCols(), h("div", { slot: "bottom" }, this.gotData && this.footerContent?.copyrightText ? h("span", null, this.footerContent.copyrightText) : null, this.gotData && this.footerContent?.bottomLinks ? (h("span", null, this.footerContent.bottomLinks.map(link => {
            if (!link.linkHref) {
                return h("span", null, link.linkText);
            }
            let linkId = this.uniqueId(link.linkText);
            return (h("a", { href: link.linkHref, ...(link.openInNewWindow && { target: '_blank' }), title: link.linkText, id: linkId }, link.linkText));
        }))) : null))));
    }
    renderSocialMeidaIconListElements() {
        return (this.gotData &&
            this.footerContent?.socialmedialinks.map(link => {
                let linkText = getSocialMediaIconsByType(link.linkType, '#00A0D6');
                let linkId = this.uniqueId(link.linkText);
                return (h("li", null, h("a", { href: link.linkHref, ...(link.openInNewWindow && { target: '_blank' }), title: link.linkText, innerHTML: linkText, id: linkId })));
            }));
    }
    renderSwanComponent() {
        return (this.showSwan && (h("div", { class: "swan-wrapper" }, h("div", { class: "separator" }), h("pn-swan", { language: this.language, "license-number": this.footerContent?.swanInfo?.swanLicense, "link-to": this.footerContent?.swanInfo?.swanLink }))));
    }
    renderDotComFooter() {
        return (h(Host, { language: this.language, market: this.market, environment: this.environment }, h("pn-site-footer", { theme: this.theme, url: this.siteDefinition?.url ?? '' }, this.renderCols(), h("slot", { name: "middle-extra" }), h("slot", { name: "middle-extra-mobile" }), h("div", { slot: "bottom" }, h("div", { class: `social-media ${this.showSwan ? 'social-media--swan' : ''}` }, h("ul", null, this.renderSocialMeidaIconListElements()), this.renderSwanComponent()), h("div", { class: "copyright" }, this.gotData && this.footerContent?.copyrightText ? h("span", null, this.footerContent.copyrightText) : null, this.gotData && this.footerContent?.bottomLinks ? h("ul", null, this.renderBottomLinks()) : null)))));
    }
    render() {
        switch (this.theme) {
            case 'dotcom':
                return this.renderDotComFooter();
            default:
                return this.renderDefaultFooter();
        }
    }
    static get is() { return "pn-marketweb-sitefooter"; }
    static get originalStyleUrls() {
        return {
            "$": ["pn-marketweb-sitefooter.scss"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["pn-marketweb-sitefooter.css"]
        };
    }
    static get properties() {
        return {
            "market": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "market",
                "reflect": true,
                "defaultValue": "'se'"
            },
            "language": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "language",
                "reflect": true,
                "defaultValue": "'sv'"
            },
            "environment": {
                "type": "string",
                "mutable": true,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "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"
            },
            "siteDomainInUrls": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "Adjusts the menus URLs"
                },
                "attribute": "site-domain-in-urls",
                "reflect": false,
                "defaultValue": "false"
            },
            "cache": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "If the component should use cached requests"
                },
                "attribute": "cache",
                "reflect": false,
                "defaultValue": "false"
            },
            "theme": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "dotcom prop"
                },
                "attribute": "theme",
                "reflect": true,
                "defaultValue": "'default'"
            },
            "backgroundcolor": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "dotcom backgroundcolor"
                },
                "attribute": "backgroundcolor",
                "reflect": true,
                "defaultValue": "'darkestblue'"
            },
            "showSwan": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "show-swan",
                "reflect": false,
                "defaultValue": "false"
            },
            "headingLevel": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "attribute": "heading-level",
                "reflect": false,
                "defaultValue": "\"h2\""
            }
        };
    }
    static get states() {
        return {
            "siteDefinition": {},
            "footerContent": {},
            "i18n": {},
            "gotData": {},
            "fetchingData": {}
        };
    }
    static get elementRef() { return "hostElement"; }
    static get watchers() {
        return [{
                "propName": "language",
                "methodName": "onLanguageChange"
            }, {
                "propName": "market",
                "methodName": "onMarketChange"
            }];
    }
}
//# sourceMappingURL=pn-marketweb-sitefooter.js.map
