import { Component, Prop, State, h } from '@stencil/core';
import { simpleFetch } from '@utils/HttpUtils';
import { createNode, getSvgInnerHTML } from '@utils/DomUtils';
import { cssIcons } from '@utils/Icons.js';
import packageInfo from '../../../package.json';
const SVG_SOURCE_URL = `https://unpkg.com/${packageInfo.name}@${packageInfo.version}/dist/lib/images/svg-sprite.svg`;
// putting the svgNode in global is a bit ugly, but this way we need only a single createNode
let svgNode = null;
const getSvg = simpleFetch(SVG_SOURCE_URL).then(res => (svgNode = createNode(res)));
export class Icon {
    constructor() {
        /**
         * Icon Name – see Styles/Icons/Available Icons for possbile names
         */
        this.name = 'message';
    }
    connectedCallback() {
        if (!svgNode) {
            getSvg
                .then(() => (this.svgNode = svgNode))
                .catch(err => {
                console.log('SVG Sprint could not be loaded – ', err);
            });
        }
        else {
            this.svgNode = svgNode;
        }
    }
    isCssIcon() {
        return cssIcons.includes(this.name);
    }
    getIcon() {
        if (this.isCssIcon() || !this.svgNode)
            return '';
        const icon = this.svgNode.querySelector(`#picto-${this.name}`);
        if (!icon) {
            console.error(`Icon ${this.name} could not be found. You can check the available icons in the styleguide. Please check that you are using the current vesion of the SwissRe UI Library.`);
            return '';
        }
        const viewBox = icon.getAttribute('viewBox');
        return `<svg class="sc-sr-icon" viewBox="${viewBox}">${getSvgInnerHTML(icon)}</svg>`;
    }
    render() {
        if (this.isCssIcon()) {
            return h("span", { class: "Icon", "data-icon": this.name });
        }
        return h("span", { class: "Icon", "data-picto": this.name, innerHTML: this.getIcon() });
    }
    static get is() { return "sr-icon"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() { return {
        "$": ["_Icon-component.scss"]
    }; }
    static get styleUrls() { return {
        "$": ["_Icon-component.css"]
    }; }
    static get properties() { return {
        "name": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": "Icon Name \u2013 see Styles/Icons/Available Icons for possbile names"
            },
            "attribute": "name",
            "reflect": false,
            "defaultValue": "'message'"
        }
    }; }
    static get states() { return {
        "svgNode": {}
    }; }
}
