import { h } from '../webcomponents.core.js';

import './chunk-de721f0a.js';
import { x as concatAll, j as map, y as interval } from './chunk-fec5a75d.js';
import { c as pluck } from './chunk-d51357a9.js';
import { k as BaseApi, l as ConfigService, j as DomUtil } from './chunk-6163e267.js';
import { a as AppService, b as HttpService } from './chunk-0afee227.js';

/*
//
// Base class for vanilla js webcomponents
//
*/
class WebComponent extends HTMLElement {

    constructor() {
        super();
    }

    // to be overridden in subclass
    async init() {
    }

    render() {
    }

    definePublicMethods() {
    }

    attributeChangedCallback(name, oldVal, newVal) {
    }

    //

    connectedCallback() {
        let shadowRoot;
        if (!this.shadowRoot) {
            if (this.shadow) {
                shadowRoot = this.root = this.attachShadow({
                    mode: 'open'
                });
            } else {
                shadowRoot = this.root = this;
            }
        } else {
            shadowRoot = this.root = this.shadowRoot;
        }
        shadowRoot.appendChild(this.template.content.cloneNode(true));
        this.el = this.root.querySelector('.content');
        this.data = {};
        // this.html = this.html.bind(this);
        this.getData = this.getData.bind(this);
        this.setData = this.setData.bind(this);
        if (this.definePublicMethods) {
            this.definePublicMethods();
        }
        if (this.init) {
            this.init = this.init.bind(this);
        }
        if (this.dataJson) {
            this.data = JSON.parse(this.dataJson);
        }
        if (this.init) {
            this.init().then(() => {
                this.render();
            });
        } else {
            this.render();
        }
    }

    set html(markup) {
        if (this.el && markup) {
            this.el.innerHTML = markup;
        }
    }

    get template() {
        if (this._template) {
            return this._template;
        }
        this._template = document.createElement('template');
        let styles = document.createElement('style');
        let content = document.createElement('div');
        let imports = document.createElement('head');
        imports.innerHTML = this.imports || ``;
        styles.innerHTML = this.styles || ``;
        content.innerHTML = this.htmlTemplate || ``;
        content.className = 'content';
        this._template.content.appendChild(styles);
        this._template.content.appendChild(imports);
        this._template.content.appendChild(content);
        return this._template;
    }

    declareProp(propName, getFn, setFn) {
        let obj = {};
        if (!getFn) {
            getFn = function () {
                if (this.getAttribute(propName) !== null) {
                    return this.getAttribute(propName);
                } else {
                    return '';
                }
            };
        }
        if (!setFn) {
            setFn = function (value) {
                this.setAttribute(propName, value);
            };
        }
        if (propName === 'data-json') {
            setFn = (value) => {
                let data = JSON.parse(value);
                Object.keys(data).forEach((k) => {
                    this.data[k] = data[k];
                });
                this.setAttribute(propName, value);
            };
        }
        obj[this.kebabToLowerCamelCase(propName)] = {get: getFn, set: setFn};
        Object.defineProperties(this, obj);
    }

    dispatch(eventName, detail) {
        this.dispatchEvent(new CustomEvent(eventName, {bubbles: true, detail: detail}));
    }

    setState(state) {
        if (typeof state === 'string' && !this.isJson(state)) {
            console.error('setState only accepts an object as argument');
            return;
        }
        if (typeof state === 'string' && this.isJson(state)) {
            state = JSON.parse(state);
        }
        this.state = {...this.state, ...state};
        this.render();
    }

    setData(object, extend) {
        if (extend) {
            Object.keys(object).forEach((k, i) => {
                this.data[k] = object[k];
            });
        } else {
            this.data = object;
        }
        this.setState({data: this.data});
        // this.render();
    }

    getData() {
        return this.data;
    }

    isJson(jsonString) {
        try {
            let o = JSON.parse(jsonString);
            if (o && typeof o === "object") {
                return o;
            }
        } catch (e) {
        }
        return false;
    }

    kebabToLowerCamelCase(str) {
        let string = str.charAt(0).toLowerCase() + str.slice(1);
        return string.replace(/(\-\w)/g, function (m) {
            return m[1].toUpperCase();
        });
    }

}

const props = ['label', 'foo', 'foo2', 'test', 'data-json'];
window.customElements.define('web-comp-runtime', class extends WebComponent {
    constructor() {
        super();
        this.defineProps(props);
        this.styles = `:host .content { 
            background: var(--ema-primary,black); 
            color:white;padding:15px;
        }`;
    }
    render() {
        this.html = `
      
          <h5>${this.label}: - foo =  ${this['data'].foo}  - sliderV: ${this['data'].sliderV}</h5>
       
          <ema-slider value="${this['data'].sliderV}"></ema-slider>
          <ema-card>
            <ema-card-header>
                <span class="ema-card-header-title">${this.label}</span>
                <span class="ema-card-header-subtitle">${this['data'].foo}</span>
            </ema-card-header>
            <ema-card-content>
                Content goes here
            </ema-card-content>
            <ema-card-footer>
                <button class="btn btn-primary">Action!</button>
            </ema-card-footer>
            </ema-card>
        `;
    }
    attributeChangedCallback(name, oldVal, newVal) {
        this.preRender();
    }
    defineProps(props) {
        props.forEach((propName) => {
            let get, set;
            if (propName === 'test') {
                get = () => {
                    return this.getAttribute(propName) + ': CUSTOM GET';
                };
                set = (value) => {
                    this.setAttribute(propName, value + ': CUSTOM SET');
                };
            }
            this.declareProp(propName, get, set);
        });
    }
    hide() {
        this.root.querySelector('.content').style.display = 'none';
    }
    definePublicMethods() {
        this.hide = this.hide.bind(this);
    }
});

class AppDev {
    constructor() {
        this.authenticated = false;
        this.clientId = 'e-be';
        this.app = AppService.instance;
        this.api = new BaseApi();
        this.http = HttpService.instance;
        this.config = ConfigService.instance;
        this.translation = this.app.translation;
        this.data = this.app.data;
    }
    async runTests() {
        let repeaterMockData = [];
        let data$ = this.http.get('assets/data/mock-data.json');
        data$.pipe(pluck('data'), concatAll(), map((item) => item['data']['attributes'])).subscribe((arg) => {
            repeaterMockData.push(arg);
        }, undefined, () => {
            console.log('complete');
            this.data = Object.assign({}, this.data, { repeaterMockData: repeaterMockData });
        });
        let webcomponent = this.el.querySelector('web-comp-runtime');
        interval(3000).subscribe((arg) => {
            if (webcomponent) {
                webcomponent['label'] = Math.random();
                webcomponent['setData'](this.data);
            }
        });
        let dialogComponent = document.getElementById('app-dialog');
        if (dialogComponent) {
            dialogComponent['setConfirmHandler'](function () {
                console.log('dialogConfirmHandler called');
            });
        }
    }
    debuggerTest() {
        let emaDebugger = document.querySelector('ema-debugger');
        if (emaDebugger) {
            emaDebugger.open();
            interval(1500).subscribe((i) => {
                if (i <= this.data.dwpData.length - 1) {
                    if (emaDebugger) {
                        emaDebugger.dataJson = JSON.stringify(this.data.dwpData[i]);
                    }
                }
            });
        }
    }
    componentDidLoad() {
        this.runTests();
    }
    render() {
        return (h("div", null,
            h("div", { class: 'container' }, this.data &&
                h("div", null,
                    h("ema-tabs", null,
                        h("ema-tab-header", { slot: "header", name: "tab1" }, "Div"),
                        h("ema-tab-content", { slot: "content", name: "tab1" },
                            h("div", { class: "btn-group mb-3", role: "group", "aria-label": "Basic examples" },
                                h("button", { class: 'btn ', onClick: ev => this.runTests() }, "Run tests"),
                                h("button", { class: 'btn ', onClick: ev => this.debuggerTest() }, "Open debugger"),
                                h("button", { class: 'btn ', onClick: ev => document.getElementById('login-modal')['show']() }, "Login modal"),
                                h("button", { class: 'btn ', onClick: () => this.app.showFlashMessage('zis is ze message', 'secondary', 3000) }, "Show flashmessage"),
                                h("button", { class: 'btn ', onClick: ev => document.querySelector('ema-dialog').alert('yep') }, "Alert"),
                                h("button", { class: 'btn ', onClick: ev => document.querySelector('ema-dialog').confirm('Are you sure?', function () { console.log('confirmed'); }) }, "Confirm"),
                                h("button", { class: 'btn ', onClick: ev => document.querySelector('ema-dialog').confirm('Are you sure?') }, "Confirm2"),
                                h("button", { class: 'btn ', onClick: ev => document.querySelector('ema-dialog').notice('Notice content') }, "Notice"),
                                h("button", { class: 'btn ', onClick: ev => DomUtil.fadeIn(document.getElementById('logo')) }, "fIn"),
                                h("button", { class: 'btn ', onClick: ev => DomUtil.fadeOut(document.getElementById('logo')) }, "fOut")),
                            h("web-comp", { label: "runtime webcomponent", test: "test", "data-json": JSON.stringify({ foo: 'bar', sliderV: 0 }) }),
                            h("web-comp-runtime", { label: "runtime webcomponent", "data-json": JSON.stringify({ foo: 'bar', sliderV: 0 }) }),
                            h("ema-collapsible", { label: 'config', collapsed: true },
                                h("ema-json-viewer", { "json-url": '/assets/config.json', allowCopy: true }))),
                        h("ema-tab-header", { slot: "header", name: "tab6" }, "Flip board"),
                        h("ema-tab-content", { slot: "content", name: "tab6" },
                            h("ema-layout", { class: 'layout-grid-fill flip-board' }, this.data.manifest.components.map((item, i) => {
                                return h("ema-flip", { class: "item", "flip-events": "click", "flip-back-events": "click", "flip-duration": "350", "flip-timing-function": "ease-in-out" },
                                    h("div", { slot: "front" },
                                        h("ema-card", null,
                                            h("ema-card-header", null,
                                                h("span", { class: "ema-card-header-title" }, (i + 1)),
                                                h("span", { class: "ema-card-header-subtitle" }, '<ema-flip>')),
                                            h("ema-card-content", null, "info goes here"),
                                            h("ema-card-footer", null,
                                                h("button", { class: 'btn btn-primary' }, "flip me")))),
                                    h("div", { slot: "back" },
                                        h("ema-card", null,
                                            h("ema-card-header", null,
                                                h("span", { class: "ema-card-header-title" }, "Flip card back"),
                                                h("span", { class: "ema-card-header-subtitle" }, "Subtitle")),
                                            h("ema-card-content", null, "Content goes here"),
                                            h("ema-card-footer", null,
                                                h("button", { class: 'btn btn-primary' }, "Action!")))));
                            }))),
                        h("ema-tab-header", { slot: "header", name: "tab5" }, "Layout"),
                        h("ema-tab-content", { slot: "content", name: "tab5" },
                            h("h5", null, ".layout-header-sidebar20-content80-footer"),
                            h("ema-layout", { class: 'layout-header-sidebar20-content80-footer', "grid-gap": '5px' },
                                h("header", null, "My header"),
                                h("aside", null, "Sidebar"),
                                h("article", null,
                                    h("h4", null, "2 column, header and footer"),
                                    h("p", null, "Example content.")),
                                h("footer", null, "My footer")),
                            h("h5", null, ".layout-grid-fill"),
                            h("ema-layout", { class: 'layout-grid-fill' }, this.data.mockData.data.map((item) => {
                                return h("article", { class: 'text-center' },
                                    h("h4", null, item.data.attributes.title),
                                    h("ema-lazy-img", { src: item.links.self }));
                            })),
                            this.data.mockData.data.map((item) => {
                                return h("ema-layout", { class: 'layout-header-content80-sidebar20-footer mb-3' },
                                    h("header", null,
                                        h("h4", null, item.data.type)),
                                    h("article", null,
                                        h("h3", null, item.data.attributes.title),
                                        h("p", null, item.data.attributes.body)),
                                    h("aside", null,
                                        h("ema-lazy-img", { src: item.links.self })),
                                    h("footer", null, item.data.attributes.email));
                            })),
                        h("ema-tab-header", { slot: "header", name: "repeater" }, "Repeater"),
                        h("ema-tab-content", { slot: "content", name: "repeater" },
                            h("h4", null, "repeater-component"),
                            h("ema-repeater", { element: "ul", template: '<li><h5>${title}</h5><p>${body}</p></li>', "data-json": JSON.stringify(this.data.repeaterMockData) }))))),
            h("footer", null)));
    }
    static get is() { return "ema-app-dev"; }
    static get properties() { return {
        "authenticated": {
            "state": true
        },
        "clientId": {
            "type": String,
            "attr": "client-id"
        },
        "data": {
            "state": true
        },
        "el": {
            "elementRef": true
        }
    }; }
    static get style() { return ":root{--ema-color:#343a40;--ema-primary:#007bff;--ema-secondary:#6c757d;--ema-success:#28a745;--ema-info:#17a2b8;--ema-warning:#ffc107;--ema-danger:#dc3545;--ema-light:#f8f9fa;--ema-dark:#343a40;--ema-background:#fff;--ema-background-diap:rgba(29,29,29,0.97);--ema-border-color:#c5c9cd;--ema-border:1px solid #c5c9cd;--ema-border-radius:3px 3px 3px 3px;--ema-box-shadow:1px 1px 10px 1px #ccc;--ema-margin:0.25rem;--ema-margin-sm:0.5rem;--ema-margin-md:1rem;--ema-margin-lg:1.5rem;--ema-margin-xl:2rem;--ema-padding:0.25rem;--ema-padding-sm:0.5rem;--ema-padding-md:1rem;--ema-padding-lg:1.5rem;--ema-padding-xl:2rem;--ema-gray-100:#f8f9fa;--ema-gray-200:#e9ecef;--ema-gray-300:#dee2e6;--ema-gray-400:#ced4da;--ema-gray-500:#adb5bd;--ema-gray-600:#868e96;--ema-gray-700:#495057;--ema-gray-800:#343a40;--ema-gray-900:#212529}ema-app-dev .flip-board .item{width:240px;justify-self:center;margin:0 auto}ema-app-dev .flip-board .item .ema-card-header-title{font-weight:700}ema-app-dev .flip-board .item .ema-flip__front ema-card{text-align:center}ema-app-dev .flip-board .item .ema-flip__back ema-card{text-align:center;background:#e9e9e9}ema-app-dev .ema-splitter-container{position:absolute;padding-top:0;padding-bottom:114px;left:0;height:100%;width:100%}ema-app-dev .ema-splitter-container ema-splitter div[slot]{height:100%;width:100%;display:-ms-flexbox;display:flex;overflow:hidden;-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center}ema-app-dev .ema-splitter-container ema-splitter div[slot] ion-icon{display:block;font-size:3rem;color:#007bff}ema-app-dev .ema-splitter-container ema-splitter .main .column-2{background:#dee2e6;border-radius:50%}"; }
}

class Flip {
    constructor() {
        this.events = { flipEvents: [], flipBackEvents: [] };
    }
    componentWillLoad() {
        this.init();
    }
    componentDidLoad() {
        const duration = this.flipDuration || 400;
        const timingFunction = this.flipTimingFunction || 'ease-in';
        ['front', 'back']
            .forEach(key => {
            const el = this.element.querySelector(`.ema-flip__${key}`);
            el['style'].transition = `all ${duration / 1000}s ${timingFunction}`;
        });
    }
    componentWillUpdate() {
        if (this.isFlipped !== undefined) {
            this.flipState = this.isFlipped;
        }
    }
    init() {
        if (this.isFlipped !== undefined) {
            this.flipState = this.isFlipped;
        }
        else if (this.flipEvents !== undefined) {
            ['flipEvents', 'flipBackEvents'].forEach(key => {
                this.events[key] = (this[key]) ?
                    this[key].split(',') :
                    [];
            });
            const allEvents = [...this.events.flipEvents, ...this.events.flipBackEvents];
            allEvents
                .filter((eventType, index) => allEvents.indexOf(eventType) === index)
                .forEach(eventType => this.element.addEventListener(eventType, (evt) => this.processFlip(evt)));
            this.flipState = false;
        }
    }
    processFlip(evt) {
        const eventType = evt.type;
        if (this.flipState && this.events.flipBackEvents.indexOf(eventType) !== -1) {
            this.flipState = !this.flipState;
        }
        else if (!this.flipState && this.events.flipEvents.indexOf(eventType) !== -1) {
            this.flipState = !this.flipState;
        }
    }
    flip() {
        this.flipState = !this.flipState;
        console.log(this.flipState);
    }
    render() {
        return (h("div", { class: `ema-flip ${(this.flipState ? 'ema-flip--flipped' : '')}` },
            h("div", { class: "ema-flip__front" },
                h("slot", { name: "front" })),
            h("div", { class: "ema-flip__back" },
                h("slot", { name: "back" }))));
    }
    static get is() { return "ema-flip"; }
    static get properties() { return {
        "element": {
            "elementRef": true
        },
        "flip": {
            "method": true
        },
        "flipBackEvents": {
            "type": String,
            "attr": "flip-back-events"
        },
        "flipDuration": {
            "type": Number,
            "attr": "flip-duration"
        },
        "flipEvents": {
            "type": String,
            "attr": "flip-events"
        },
        "flipState": {
            "state": true
        },
        "flipTimingFunction": {
            "type": String,
            "attr": "flip-timing-function"
        },
        "isFlipped": {
            "type": Boolean,
            "attr": "is-flipped"
        }
    }; }
    static get style() { return ":root{--ema-color:#343a40;--ema-primary:#007bff;--ema-secondary:#6c757d;--ema-success:#28a745;--ema-info:#17a2b8;--ema-warning:#ffc107;--ema-danger:#dc3545;--ema-light:#f8f9fa;--ema-dark:#343a40;--ema-background:#fff;--ema-background-diap:rgba(29,29,29,0.97);--ema-border-color:#c5c9cd;--ema-border:1px solid #c5c9cd;--ema-border-radius:3px 3px 3px 3px;--ema-box-shadow:1px 1px 10px 1px #ccc;--ema-margin:0.25rem;--ema-margin-sm:0.5rem;--ema-margin-md:1rem;--ema-margin-lg:1.5rem;--ema-margin-xl:2rem;--ema-padding:0.25rem;--ema-padding-sm:0.5rem;--ema-padding-md:1rem;--ema-padding-lg:1.5rem;--ema-padding-xl:2rem;--ema-gray-100:#f8f9fa;--ema-gray-200:#e9ecef;--ema-gray-300:#dee2e6;--ema-gray-400:#ced4da;--ema-gray-500:#adb5bd;--ema-gray-600:#868e96;--ema-gray-700:#495057;--ema-gray-800:#343a40;--ema-gray-900:#212529}.ema-flip{-webkit-perspective:1000px;perspective:1000px;text-align:center}.ema-flip__back,.ema-flip__front{position:absolute;width:inherit;height:inherit;-webkit-transform-style:preserve-3d;transform-style:preserve-3d;-webkit-backface-visibility:hidden;backface-visibility:hidden}.ema-flip__front{z-index:900;-webkit-transform:rotate3d(0,0,0,0deg);transform:rotate3d(0,0,0,0deg)}.ema-flip--flipped .ema-flip__front{z-index:900;-webkit-transform:rotateY(180deg);transform:rotateY(180deg);-ms-transform:rotateY(180deg)}.ema-flip__back{z-index:800;-webkit-transform:rotateY(-180deg);transform:rotateY(-180deg)}.ema-flip--flipped .ema-flip__back{z-index:1000;-webkit-transform:rotate3d(0,0,0,0deg);transform:rotate3d(0,0,0,0deg)}"; }
}

class LazyImg {
    componentDidLoad() {
        this.addIntersectionObserver();
    }
    componentWillUpdate() {
        if (this.src !== this.oldSrc) {
            this.addIntersectionObserver();
        }
        this.oldSrc = this.src;
    }
    handleImage() {
        const image = this.el.shadowRoot.querySelector('img');
        image.setAttribute('src', image.getAttribute('data-src'));
        image.onload = () => {
            image.removeAttribute('data-src');
        };
    }
    addIntersectionObserver() {
        if (!this.src) {
            return;
        }
        if ('IntersectionObserver' in window) {
            this.io = new IntersectionObserver((data) => {
                if (data[0].isIntersecting) {
                    this.handleImage();
                    this.removeIntersectionObserver();
                }
            });
            this.io.observe(this.el.shadowRoot.querySelector('img'));
        }
        else {
            this.handleImage();
        }
    }
    removeIntersectionObserver() {
        if (this.io) {
            this.io.disconnect();
            this.io = null;
        }
    }
    render() {
        return (h("img", { "data-src": this.src, alt: this.alt }));
    }
    static get is() { return "ema-lazy-img"; }
    static get encapsulation() { return "shadow"; }
    static get properties() { return {
        "alt": {
            "type": String,
            "attr": "alt"
        },
        "el": {
            "elementRef": true
        },
        "oldSrc": {
            "state": true
        },
        "src": {
            "type": String,
            "attr": "src"
        }
    }; }
    static get style() { return ":root{--ema-color:#343a40;--ema-primary:#007bff;--ema-secondary:#6c757d;--ema-success:#28a745;--ema-info:#17a2b8;--ema-warning:#ffc107;--ema-danger:#dc3545;--ema-light:#f8f9fa;--ema-dark:#343a40;--ema-background:#fff;--ema-background-diap:rgba(29,29,29,0.97);--ema-border-color:#c5c9cd;--ema-border:1px solid #c5c9cd;--ema-border-radius:3px 3px 3px 3px;--ema-box-shadow:1px 1px 10px 1px #ccc;--ema-margin:0.25rem;--ema-margin-sm:0.5rem;--ema-margin-md:1rem;--ema-margin-lg:1.5rem;--ema-margin-xl:2rem;--ema-padding:0.25rem;--ema-padding-sm:0.5rem;--ema-padding-md:1rem;--ema-padding-lg:1.5rem;--ema-padding-xl:2rem;--ema-gray-100:#f8f9fa;--ema-gray-200:#e9ecef;--ema-gray-300:#dee2e6;--ema-gray-400:#ced4da;--ema-gray-500:#adb5bd;--ema-gray-600:#868e96;--ema-gray-700:#495057;--ema-gray-800:#343a40;--ema-gray-900:#212529}:host{display:block}img{max-width:100%}"; }
}

class Repeater {
    constructor() {
        this.content = [];
        this.element = "ul";
        this.template = '';
    }
    componentDidLoad() {
        this.postRender();
    }
    componentDidUpdate() {
        this.postRender();
    }
    postRender() {
        this.el.innerHTML = this.html;
    }
    async setData(content) {
        this.content = content;
    }
    async setTemplate(template) {
        this.templateString = template;
    }
    interpolate(template, obj) {
        if (typeof obj == "object") {
            for (let key in obj) {
                const find = "${" + key + "}";
                if (template.indexOf(find) > -1) {
                    template = template.replace(find, obj[key]);
                    delete obj[key];
                }
            }
        }
        return template;
    }
    render() {
        const element = this.element;
        let html = (element !== null) ? "<" + element.toLowerCase() + ">" : "";
        if (this.template) {
            this.templateString = this.template;
        }
        if (this.dataJson) {
            this.content = JSON.parse(this.dataJson);
        }
        if (Array.isArray(this.content)) {
            this.content.forEach((item) => {
                html += this.interpolate(this.templateString, item);
            });
        }
        else {
            throw new Error("Content should be an Array of objects.");
        }
        html += (element !== null) ? "</" + element.toLowerCase() + ">" : "";
        this.html = html;
        return (h("div", null));
    }
    static get is() { return "ema-repeater"; }
    static get properties() { return {
        "content": {
            "state": true
        },
        "dataJson": {
            "type": String,
            "attr": "data-json"
        },
        "el": {
            "elementRef": true
        },
        "element": {
            "type": String,
            "attr": "element"
        },
        "setData": {
            "method": true
        },
        "setTemplate": {
            "method": true
        },
        "template": {
            "type": String,
            "attr": "template"
        },
        "templateString": {
            "state": true
        }
    }; }
}

export { AppDev as EmaAppDev, Flip as EmaFlip, LazyImg as EmaLazyImg, Repeater as EmaRepeater };
