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

import './chunk-de721f0a.js';
import './chunk-fec5a75d.js';
import './chunk-d51357a9.js';
import { d as Util } from './chunk-6163e267.js';
import { a as AppService } from './chunk-0afee227.js';

class AppSwagger {
    constructor() {
        this.appService = AppService.instance;
        this.swaggerUrl = '/assets/data/apiSwagger.json';
    }
    componentWillLoad() {
        Util.fetchJson(this.swaggerUrl).then((res) => {
            this.loading = false;
            this.swagger = res;
            this.currentJsonObject = JSON.parse(JSON.stringify(res));
            console.log(this);
        });
    }
    parseSwaggerTypeAhead() {
        let searchData = [];
        this.swagger['tags'].forEach((tag) => {
            let obj = { "group": tag.name, "tags": [] };
            searchData.push(obj);
            Object.keys(this.swagger['paths']).forEach((k, i) => {
                let v = this.swagger['paths'][k];
                if (k.match(('/' + tag.name + '/'))) {
                    obj.tags.push(k);
                }
            });
        });
        return searchData;
    }
    onTypeAheadSelection(event) {
        console.log('onTypeAheadSelection');
        console.log(event.detail);
        this.currentJsonObject = JSON.parse(JSON.stringify(this.swagger.paths[event.detail.tag]));
    }
    onTypeAheadSearch(event) {
        console.log('onTypeAheadSearch');
        console.log(event.detail);
    }
    render() {
        console.log('render', this);
        return (h("div", { class: 'ema-app-swagger container' }, this.swagger &&
            h("div", null,
                h("h5", null, "api: swagger"),
                h("ema-type-ahead", { dataJson: JSON.stringify(this.parseSwaggerTypeAhead()), onSelection: ev => this.onTypeAheadSelection(ev), onSearch: ev => this.onTypeAheadSearch(ev) }),
                h("ema-json-viewer", { class: 'pt-3', dataJson: JSON.stringify(this.currentJsonObject), "allow-copy": 'true' }))));
    }
    static get is() { return "ema-app-swagger"; }
    static get properties() { return {
        "currentJsonObject": {
            "state": true
        },
        "isServer": {
            "context": "isServer"
        },
        "loading": {
            "state": true
        },
        "swagger": {
            "state": true
        }
    }; }
    static get style() { return ".ema-app-swagger{padding:10px}"; }
}

class TypeAhead {
    constructor() { }
    selectionHandler(data) {
        this.selection.emit(data);
    }
    searchHandler(data) {
        this.search.emit(data);
    }
    componentDidLoad() {
        this.data = JSON.parse(this.dataJson);
        document.addEventListener('typeAheadItemClick', (e) => {
            let inputEl = this.el.getElementsByClassName('search-input')[0];
            let wrapperEl = this.el.getElementsByClassName('ac-results-wrapper')[0];
            inputEl['value'] = e.detail['tag'];
            wrapperEl['style']['display'] = 'none';
            this.selectionHandler(e.detail);
        });
    }
    postRender() {
        setTimeout(() => {
            this.init();
        }, 100);
    }
    init() {
        let data = this.data;
        let opts = {
            data: data,
            numResults: 100,
            searchPath: '/search?q=',
            directPath: '/',
            container: this.el.querySelectorAll('.search-container')[0],
            wrapper: this.el.querySelectorAll('.ac-results-wrapper')[0],
            input: this.el.querySelectorAll('.search-input')[0],
        };
        this.autocomplete(opts);
    }
    autocomplete(options) {
        const self = this;
        let doc = document, data = options.data, contEl = options.container, resultNodes = contEl.getElementsByTagName('A'), cache = {}, handlers = {
            'enter': function (e) {
                if (e.target.parentNode === contEl && contEl.children[0].value) {
                    self.searchHandler.call(self, options.input['value']);
                    options.wrapper['style']['display'] = 'none';
                }
            },
            'up': function (e) {
                e.preventDefault();
                if (e.target.previousElementSibling && e.target.previousElementSibling.hasAttribute('href')) {
                    e.target.previousElementSibling.focus();
                }
                else if (!e.target.previousElementSibling && e.target.parentNode === contEl.lastElementChild) {
                    contEl.children[0].focus();
                }
            },
            'down': function (e) {
                e.preventDefault();
                if (e.target === contEl.children[0]) {
                    contEl.lastElementChild.children[0].focus();
                }
                else if (e.target.nextElementSibling && e.target.nextElementSibling.hasAttribute('href')) {
                    e.target.nextElementSibling.focus();
                }
            },
            'input': function (e) {
                options.wrapper['style']['display'] = 'block';
                var val = e.target.value.trim().replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
                return val ? insert(cacheFn(val, check)) : insert();
            }
        };
        function setEls() {
            var wrapEl = contEl.querySelectorAll('.ac-results-wrapper')[0];
            var i = options.numResults;
            while (i--) {
                var anchorEl = document.createElement('a');
                anchorEl.href = '#';
                anchorEl.innerHTML = 'a<i>i</i>';
                wrapEl.appendChild(anchorEl);
            }
        }
        function cacheFn(q, fn) {
            return cache[q] ? cache[q] : cache[q] = fn(q), cache[q];
        }
        function check(q) {
            var rxFn = function (s) {
                return '\\b(' + s + ')(.*)';
            }, rx = new RegExp(q.replace(/(\S+)/g, rxFn).replace(/\s+/g, ''), 'gi'), arr = [], i = data.length;
            function testFn(obj) {
                var j = obj.tags.length;
                while (j--) {
                    if (rx.test(obj.tags[j])) {
                        arr.push({
                            'tag': obj.tags[j],
                            'group': obj.group
                        });
                    }
                }
            }
            while (i--) {
                testFn(data[i]);
            }
            return arr;
        }
        function insert(d = undefined) {
            var i = options.numResults;
            while (i--) {
                if (d && d[i]) {
                    resultNodes[i].style.display = 'block';
                    resultNodes[i].firstChild.nodeValue = d[i].tag;
                    resultNodes[i].href = 'javascript:;';
                    resultNodes[i].firstElementChild.firstChild.nodeValue = d[i].group;
                    let dd = d;
                    let ii = i;
                    resultNodes[i].addEventListener('click', (e) => {
                        let customEvent = new CustomEvent('typeAheadItemClick', { detail: { tag: dd[ii].tag, group: dd[ii].group } });
                        document.dispatchEvent(customEvent);
                    });
                }
                else if (!d || !d[i]) {
                    resultNodes[i].style.display = 'none';
                }
            }
        }
        function multiHandler(e) {
            var k = e.keyCode, meth = k === 13 ? 'enter' : k === 38 ? 'up' : k === 40 ? 'down' : e.type === 'input' ? 'input' : null;
            return meth ? handlers[meth](e) : null;
        }
        function changeHandler(e) {
            window.setTimeout(function () {
                return doc.activeElement.parentNode === contEl || doc.activeElement.parentNode === contEl.lastElementChild ? null : insert();
            }, 50);
        }
        setEls();
        contEl.addEventListener('input', multiHandler);
        contEl.addEventListener('keydown', multiHandler);
        contEl.querySelectorAll('.search-button')[0].addEventListener('click', handlers.enter);
        contEl.firstElementChild.addEventListener('change', changeHandler);
    }
    ;
    render() {
        return (h("div", null,
            h("div", { class: "search-container" },
                h("input", { class: "search-input" }),
                h("svg", { class: "search-button", xmlns: "http://www.w3.org/2000/svg" },
                    h("path", { fill: "#818080", d: "m25.14381,22.4446l-5.4416,-5.4416c0.7341,-1.2095 1.1629,-2.6229 1.1641,-4.14c-0.0012,-4.4244 -3.583,-8.00627 -8.0039,-8.0086c-4.42316,0.00233 -8.00622,3.5842 -8.00622,8.0074c0,4.4209 3.58305,8.0039 8.00622,8.0039c1.5171,0 2.9317,-0.4299 4.14,-1.1629l5.4428,5.4428l2.6986,-2.701l0,0l0,0zm-17.23357,-9.5828c0.00465,-2.73478 2.21627,-4.94636 4.95097,-4.95219c2.7337,0.00583 4.9463,2.21742 4.951,4.95219c-0.0047,2.7336 -2.2173,4.9453 -4.951,4.9522c-2.7347,-0.0069 -4.94632,-2.2186 -4.95097,-4.9522z" })),
                h("div", { class: "ac-results-wrapper" })),
            this.postRender()));
    }
    static get is() { return "ema-type-ahead"; }
    static get properties() { return {
        "data": {
            "state": true
        },
        "dataJson": {
            "type": String,
            "attr": "data-json"
        },
        "el": {
            "elementRef": true
        },
        "options": {
            "type": "Any",
            "attr": "options"
        }
    }; }
    static get events() { return [{
            "name": "selection",
            "method": "selection",
            "bubbles": true,
            "cancelable": true,
            "composed": true
        }, {
            "name": "search",
            "method": "search",
            "bubbles": true,
            "cancelable": true,
            "composed": 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-type-ahead .search-container{position:relative;width:100%;height:30px}ema-type-ahead .search-container svg{position:absolute;top:0;right:0;height:100%;width:30px;z-index:11;cursor:pointer}ema-type-ahead .search-input{position:absolute;z-index:10;border-radius:0;background-color:#fff;border:1px solid #babdc0;width:inherit;display:block;font-size:70%;padding:.2ex 1ex;margin:0;height:30px}ema-type-ahead .search-input:focus{outline:none;border-color:var(--ema-padding,#007bff)}ema-type-ahead .ac-results-wrapper{position:absolute;width:inherit;top:29px;border:1px solid #babdc0;border-top:0 solid #babdc0;background-color:#fff;z-index:9}ema-type-ahead .ac-results-wrapper a{display:none;height:30px;color:inherit;vertical-align:middle;line-height:30px;padding-left:5px;text-decoration:none;text-align:left;width:100%}ema-type-ahead .ac-results-wrapper{border-bottom:1px solid #babdc0}ema-type-ahead .ac-results-wrapper a:focus,ema-type-ahead .ac-results-wrapper a:hover{background-color:#818080;color:#fff}ema-type-ahead .ac-results-wrapper i{float:right;padding-right:5px;color:#babdc0}ema-type-ahead *{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;-ms-box-sizing:border-box;box-sizing:border-box}"; }
}

export { AppSwagger as EmaAppSwagger, TypeAhead as EmaTypeAhead };
