import { __esDecorate, __runInitializers } from "tslib";
/* eslint-disable @typescript-eslint/no-explicit-any */
import { html, nothing } from 'lit';
import { property, state } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { ApiExampleGenerator } from '@api-client/core/amf/ApiExampleGenerator.js';
import { EventTypes } from '../../events/amf/EventTypes.js';
import ApiElement from '../ApiElement.js';
import '../../define/amf/api-annotation-document.js';
import '../../elements/highlight/marked-highlight.js';
import '../../md/icons/ui-icon.js';
import '../../md/button/ui-text-button.js';
import '../../md/collapse/ui-collapse.js';
/**
 * A base class for the documentation components with common templates and functions.
 */
let ApiDocumentationBase = (() => {
    let _classSuper = ApiElement;
    let _instanceExtraInitializers = [];
    let _set_domainId_decorators;
    let _queryDebouncerTimeout_decorators;
    let _queryDebouncerTimeout_initializers = [];
    let _queryDebouncerTimeout_extraInitializers = [];
    let _examplesValue_decorators;
    let _examplesValue_initializers = [];
    let _examplesValue_extraInitializers = [];
    return class ApiDocumentationBase extends _classSuper {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _set_domainId_decorators = [property({ type: String, reflect: true })];
            _queryDebouncerTimeout_decorators = [property({ type: Number })];
            _examplesValue_decorators = [state()];
            __esDecorate(this, null, _set_domainId_decorators, { kind: "setter", name: "domainId", static: false, private: false, access: { has: obj => "domainId" in obj, set: (obj, value) => { obj.domainId = value; } }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate(this, null, _queryDebouncerTimeout_decorators, { kind: "accessor", name: "queryDebouncerTimeout", static: false, private: false, access: { has: obj => "queryDebouncerTimeout" in obj, get: obj => obj.queryDebouncerTimeout, set: (obj, value) => { obj.queryDebouncerTimeout = value; } }, metadata: _metadata }, _queryDebouncerTimeout_initializers, _queryDebouncerTimeout_extraInitializers);
            __esDecorate(this, null, _examplesValue_decorators, { kind: "accessor", name: "examplesValue", static: false, private: false, access: { has: obj => "examplesValue" in obj, get: obj => obj.examplesValue, set: (obj, value) => { obj.examplesValue = value; } }, metadata: _metadata }, _examplesValue_initializers, _examplesValue_extraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        domainIdValue = __runInitializers(this, _instanceExtraInitializers);
        /**
         * The domain id of the object to render.
         * @attribute
         */
        get domainId() {
            return this.domainIdValue;
        }
        set domainId(value) {
            const old = this.domainIdValue;
            if (old === value) {
                return;
            }
            this.domainIdValue = value;
            this.requestUpdate('domainId', old);
            if (value) {
                this.processDebounce();
            }
        }
        #queryDebouncerTimeout_accessor_storage = __runInitializers(this, _queryDebouncerTimeout_initializers, void 0);
        /**
         * The timeout after which the `queryGraph()` function is called
         * in the debouncer.
         * @attribute
         */
        get queryDebouncerTimeout() { return this.#queryDebouncerTimeout_accessor_storage; }
        set queryDebouncerTimeout(value) { this.#queryDebouncerTimeout_accessor_storage = value; }
        #examplesValue_accessor_storage = (__runInitializers(this, _queryDebouncerTimeout_extraInitializers), __runInitializers(this, _examplesValue_initializers, void 0));
        get examplesValue() { return this.#examplesValue_accessor_storage; }
        set examplesValue(value) { this.#examplesValue_accessor_storage = value; }
        debounceValue = __runInitializers(this, _examplesValue_extraInitializers);
        constructor() {
            super();
            this.queryDebouncerTimeout = 1;
            this.eventsTarget.addEventListener(EventTypes.Store.graphChange, this.graphChangeHandler.bind(this));
        }
        connectedCallback() {
            super.connectedCallback();
            if (this.domainId) {
                this.processDebounce();
            }
        }
        disconnectedCallback() {
            super.disconnectedCallback();
            if (this.debounceValue) {
                clearTimeout(this.debounceValue);
                this.debounceValue = undefined;
            }
        }
        /**
         * Handler for the event dispatched by the store when the graph model change.
         */
        graphChangeHandler() {
            this.processDebounce();
        }
        /**
         * Calls the `queryGraph()` function in a debouncer.
         */
        processDebounce() {
            if (this.debounceValue) {
                clearTimeout(this.debounceValue);
            }
            this.debounceValue = setTimeout(() => {
                this.debounceValue = undefined;
                this.processGraph();
            }, this.queryDebouncerTimeout);
        }
        /**
         * The main function to use to process the AMF model.
         * To be implemented by the child classes.
         */
        processGraph() {
            // ...
        }
        /**
         * At current state there's no way to tell where to navigate when relative
         * link is clicked. To prevent 404 anchors this prevents any relative link click.
         */
        clickHandler(e) {
            const node = e.target;
            if (node.localName !== 'a') {
                return;
            }
            // target.href is always absolute, need attribute value to test for
            // relative links.
            const href = node.getAttribute('href');
            if (!href) {
                e.preventDefault();
                e.stopPropagation();
                return;
            }
            const ch0 = href[0];
            if (['.', '/'].indexOf(ch0) !== -1) {
                e.preventDefault();
                e.stopPropagation();
            }
        }
        /**
         * A handler for the section toggle button click.
         */
        sectionToggleClickHandler(e) {
            const button = e.currentTarget;
            const prop = button.dataset.ctrlProperty;
            if (!prop) {
                return;
            }
            ;
            this[prop] = !this[prop];
        }
        /**
         * @param examples The list of examples to evaluate
         * @param mediaType The media type to use with examples processing.
         */
        evaluateExamples(examples, mediaType) {
            return examples.map((example) => this.evaluateExample(example, mediaType));
        }
        /**
         * @param example The example to evaluate
         * @param mediaType The media type to use with examples processing.
         */
        evaluateExample(example, mediaType) {
            let value;
            if (mediaType) {
                const generator = new ApiExampleGenerator();
                value = generator.read(example, mediaType);
            }
            else {
                value = example.value || '';
            }
            const { name, displayName } = example;
            const label = displayName || name;
            const result = {
                ...example,
                renderValue: value,
            };
            if (label && !label.startsWith('example_')) {
                result.label = label;
            }
            return result;
        }
        /**
         * @returns The template for the section toggle button
         */
        sectionToggleTemplate(ctrlProperty) {
            const label = this[ctrlProperty] ? 'Hide' : 'Show';
            return html `
      <ui-text-button class="section-toggle">
        ${label} <ui-icon icon="arrowDropDown" role="presentation" class="toggle-icon"></ui-icon>
      </ui-text-button>
    `;
        }
        /**
         * @param label The section label.
         * @param openedProperty The name of the element property to be toggled when interacting with the toggle button.
         * @param content The content to render.
         * @returns The template for a toggle section with a content.
         */
        paramsSectionTemplate(label, openedProperty, content, opts = {}) {
            const opened = this[openedProperty];
            const { innerSection } = opts;
            const containerClasses = {
                'params-section': !innerSection,
                'surface2': !innerSection,
                'inner-section': !!innerSection,
            };
            const titleClasses = {
                'params-title': true,
                opened,
            };
            return html `
      <div class="${classMap(containerClasses)}" data-controlled-by="${openedProperty}">
        <div
          class="${classMap(titleClasses)}"
          data-ctrl-property="${openedProperty}"
          @click="${this.sectionToggleClickHandler}"
        >
          <span class="label">${label}</span>
          ${this.sectionToggleTemplate(openedProperty)}
        </div>
        <ui-collapse .open="${opened}"> ${content} </ui-collapse>
      </div>
    `;
        }
        /**
         * @param model The parameter to render.
         * @param dataName Optional data-name for this parameter
         * @returns The template for the schema item document
         */
        schemaItemTemplate(model, dataName) {
            return html `
      <api-parameter-document
        .parameter="${model}"
        class="property-item"
        data-name="${ifDefined(dataName)}"
      ></api-parameter-document>
    `;
        }
        /**
         * @param description The description to render.
         * @returns The template for the markdown description.
         */
        descriptionTemplate(description) {
            if (!description) {
                return '';
            }
            return html ` <div class="api-description">
      <marked-highlight .markdown="${description}" sanitize @click="${this.clickHandler}">
        <div slot="markdown-html" class="markdown-body text-selectable"></div>
      </marked-highlight>
    </div>`;
        }
        /**
         * @returns The template for the custom domain properties
         */
        customDomainPropertiesTemplate(customDomainProperties = []) {
            if (!customDomainProperties.length) {
                return '';
            }
            return html ` <api-annotation-document .customProperties="${customDomainProperties}"></api-annotation-document> `;
        }
        /**
         * @returns The template for the examples section.
         */
        examplesTemplate() {
            const examples = this.examplesValue;
            if (!Array.isArray(examples)) {
                return nothing;
            }
            const filtered = examples.filter((item) => !!item.renderValue);
            if (!filtered.length) {
                return nothing;
            }
            return html ` <div class="examples">${filtered.map((item) => this.exampleTemplate(item))}</div> `;
        }
        /**
         * @returns The template for a single example
         */
        exampleTemplate(item) {
            const { description, renderValue, label } = item;
            return html `
      <details class="schema-example">
        <summary>Example${label ? `: ${label}` : ''}</summary>
        <div class="example-content">
          ${description ? html `<div class="example-description text-selectable">${description}</div>` : ''}
          <pre class="code-value text-selectable"><code>${renderValue}</code></pre>
        </div>
      </details>
    `;
        }
    };
})();
export { ApiDocumentationBase };
//# sourceMappingURL=ApiDocumentationBase.js.map