import { __esDecorate, __runInitializers } from "tslib";
import { html, LitElement, nothing } from 'lit';
import { property, state } from 'lit/decorators.js';
import { DomainAssociationKind, DomainEntityKind, DomainPropertyKind } from '@api-client/core/models/kinds.js';
let DomainValidationReport = (() => {
    let _classSuper = LitElement;
    let _report_decorators;
    let _report_initializers = [];
    let _report_extraInitializers = [];
    let _domain_decorators;
    let _domain_initializers = [];
    let _domain_extraInitializers = [];
    let _withAutoFix_decorators;
    let _withAutoFix_initializers = [];
    let _withAutoFix_extraInitializers = [];
    let _infoCount_decorators;
    let _infoCount_initializers = [];
    let _infoCount_extraInitializers = [];
    let _warningCount_decorators;
    let _warningCount_initializers = [];
    let _warningCount_extraInitializers = [];
    let _errorCount_decorators;
    let _errorCount_initializers = [];
    let _errorCount_extraInitializers = [];
    let _visibleSeverities_decorators;
    let _visibleSeverities_initializers = [];
    let _visibleSeverities_extraInitializers = [];
    let _filteredReport_decorators;
    let _filteredReport_initializers = [];
    let _filteredReport_extraInitializers = [];
    return class DomainValidationReport extends _classSuper {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _report_decorators = [property({ type: Array })];
            _domain_decorators = [property({ type: Object })];
            _withAutoFix_decorators = [property({ type: Boolean })];
            _infoCount_decorators = [state()];
            _warningCount_decorators = [state()];
            _errorCount_decorators = [state()];
            _visibleSeverities_decorators = [state()];
            _filteredReport_decorators = [state()];
            __esDecorate(this, null, _report_decorators, { kind: "accessor", name: "report", static: false, private: false, access: { has: obj => "report" in obj, get: obj => obj.report, set: (obj, value) => { obj.report = value; } }, metadata: _metadata }, _report_initializers, _report_extraInitializers);
            __esDecorate(this, null, _domain_decorators, { kind: "accessor", name: "domain", static: false, private: false, access: { has: obj => "domain" in obj, get: obj => obj.domain, set: (obj, value) => { obj.domain = value; } }, metadata: _metadata }, _domain_initializers, _domain_extraInitializers);
            __esDecorate(this, null, _withAutoFix_decorators, { kind: "accessor", name: "withAutoFix", static: false, private: false, access: { has: obj => "withAutoFix" in obj, get: obj => obj.withAutoFix, set: (obj, value) => { obj.withAutoFix = value; } }, metadata: _metadata }, _withAutoFix_initializers, _withAutoFix_extraInitializers);
            __esDecorate(this, null, _infoCount_decorators, { kind: "accessor", name: "infoCount", static: false, private: false, access: { has: obj => "infoCount" in obj, get: obj => obj.infoCount, set: (obj, value) => { obj.infoCount = value; } }, metadata: _metadata }, _infoCount_initializers, _infoCount_extraInitializers);
            __esDecorate(this, null, _warningCount_decorators, { kind: "accessor", name: "warningCount", static: false, private: false, access: { has: obj => "warningCount" in obj, get: obj => obj.warningCount, set: (obj, value) => { obj.warningCount = value; } }, metadata: _metadata }, _warningCount_initializers, _warningCount_extraInitializers);
            __esDecorate(this, null, _errorCount_decorators, { kind: "accessor", name: "errorCount", static: false, private: false, access: { has: obj => "errorCount" in obj, get: obj => obj.errorCount, set: (obj, value) => { obj.errorCount = value; } }, metadata: _metadata }, _errorCount_initializers, _errorCount_extraInitializers);
            __esDecorate(this, null, _visibleSeverities_decorators, { kind: "accessor", name: "visibleSeverities", static: false, private: false, access: { has: obj => "visibleSeverities" in obj, get: obj => obj.visibleSeverities, set: (obj, value) => { obj.visibleSeverities = value; } }, metadata: _metadata }, _visibleSeverities_initializers, _visibleSeverities_extraInitializers);
            __esDecorate(this, null, _filteredReport_decorators, { kind: "accessor", name: "filteredReport", static: false, private: false, access: { has: obj => "filteredReport" in obj, get: obj => obj.filteredReport, set: (obj, value) => { obj.filteredReport = value; } }, metadata: _metadata }, _filteredReport_initializers, _filteredReport_extraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #report_accessor_storage = __runInitializers(this, _report_initializers, []
        /**
         * The domain that was validated.
         * This is used to provide context for the validation report.
         */
        );
        /**
         * The generated report of domain validation.
         */
        get report() { return this.#report_accessor_storage; }
        set report(value) { this.#report_accessor_storage = value; }
        #domain_accessor_storage = (__runInitializers(this, _report_extraInitializers), __runInitializers(this, _domain_initializers, void 0));
        /**
         * The domain that was validated.
         * This is used to provide context for the validation report.
         */
        get domain() { return this.#domain_accessor_storage; }
        set domain(value) { this.#domain_accessor_storage = value; }
        #withAutoFix_accessor_storage = (__runInitializers(this, _domain_extraInitializers), __runInitializers(this, _withAutoFix_initializers, false
        /**
         * The number of issues with the severity of "info".
         */
        ));
        /**
         * When set to true, the UI will include an "Auto fix" button
         * that allows the user to attempt to automatically fix issues in the report.
         * The host must handle the `autofix` event to perform the actual fixing.
         * @attribute
         */
        get withAutoFix() { return this.#withAutoFix_accessor_storage; }
        set withAutoFix(value) { this.#withAutoFix_accessor_storage = value; }
        #infoCount_accessor_storage = (__runInitializers(this, _withAutoFix_extraInitializers), __runInitializers(this, _infoCount_initializers, 0
        /**
         * The number of issues with the severity of "warning".
         */
        ));
        /**
         * The number of issues with the severity of "info".
         */
        get infoCount() { return this.#infoCount_accessor_storage; }
        set infoCount(value) { this.#infoCount_accessor_storage = value; }
        #warningCount_accessor_storage = (__runInitializers(this, _infoCount_extraInitializers), __runInitializers(this, _warningCount_initializers, 0
        /**
         * The number of issues with the severity of "error".
         */
        ));
        /**
         * The number of issues with the severity of "warning".
         */
        get warningCount() { return this.#warningCount_accessor_storage; }
        set warningCount(value) { this.#warningCount_accessor_storage = value; }
        #errorCount_accessor_storage = (__runInitializers(this, _warningCount_extraInitializers), __runInitializers(this, _errorCount_initializers, 0
        /**
         * Controls which severity levels are currently shown.
         * Determines which validation messages are filtered and displayed.
         */
        ));
        /**
         * The number of issues with the severity of "error".
         */
        get errorCount() { return this.#errorCount_accessor_storage; }
        set errorCount(value) { this.#errorCount_accessor_storage = value; }
        #visibleSeverities_accessor_storage = (__runInitializers(this, _errorCount_extraInitializers), __runInitializers(this, _visibleSeverities_initializers, new Set()
        /**
         * Cached filtered report based on current severity filters.
         * This improves performance by avoiding re-filtering on every render.
         */
        ));
        /**
         * Controls which severity levels are currently shown.
         * Determines which validation messages are filtered and displayed.
         */
        get visibleSeverities() { return this.#visibleSeverities_accessor_storage; }
        set visibleSeverities(value) { this.#visibleSeverities_accessor_storage = value; }
        #filteredReport_accessor_storage = (__runInitializers(this, _visibleSeverities_extraInitializers), __runInitializers(this, _filteredReport_initializers, []));
        /**
         * Cached filtered report based on current severity filters.
         * This improves performance by avoiding re-filtering on every render.
         */
        get filteredReport() { return this.#filteredReport_accessor_storage; }
        set filteredReport(value) { this.#filteredReport_accessor_storage = value; }
        willUpdate(cp) {
            super.willUpdate(cp);
            if (cp.has('report')) {
                this.computeIssueCounters();
                this.setDefaultFilters();
                this.updateFilteredReport();
            }
            if (cp.has('visibleSeverities')) {
                this.updateFilteredReport();
            }
        }
        /**
         * Computes the number of issues in the report based on their severity.
         * This method is called whenever the `report` is updated.
         */
        computeIssueCounters() {
            this.infoCount = this.report.filter((validation) => validation.severity === 'info').length;
            this.warningCount = this.report.filter((validation) => validation.severity === 'warning').length;
            this.errorCount = this.report.filter((validation) => validation.severity === 'error').length;
        }
        /**
         * Sets the default filters based on available issues.
         * By default shows errors. If no errors, shows warnings. Never shows notices by default.
         */
        setDefaultFilters() {
            if (this.errorCount > 0) {
                this.visibleSeverities = new Set(['error']);
            }
            else if (this.warningCount > 0) {
                this.visibleSeverities = new Set(['warning']);
            }
            else {
                this.visibleSeverities = new Set();
            }
        }
        /**
         * Updates the filtered report based on the current severity filters.
         * This method is called whenever the visibility filters change.
         */
        updateFilteredReport() {
            this.filteredReport = this.report.filter((validation) => this.visibleSeverities.has(validation.severity));
        }
        /**
         * Handles the filter button click events.
         * Toggles the visibility of validation messages by severity.
         */
        handleFilterClick(e) {
            const target = e.target;
            const severity = target.dataset.severity;
            if (!severity) {
                return;
            }
            const newVisibleSeverities = new Set(this.visibleSeverities);
            if (newVisibleSeverities.has(severity)) {
                newVisibleSeverities.delete(severity);
            }
            else {
                newVisibleSeverities.add(severity);
            }
            this.visibleSeverities = newVisibleSeverities;
        }
        /**
         * A handler for the "Open" button click event.
         * It prepares the Intent data to be used to run the activity
         * that will open the corresponding issue.
         */
        handleOpenIssue(e) {
            const target = e.target;
            const index = target.dataset.index;
            if (!index) {
                return;
            }
            const validation = this.filteredReport[Number(index)];
            if (!validation) {
                return;
            }
            const { key, kind, parent } = validation;
            const data = {};
            if (kind === DomainEntityKind) {
                data.selection = {
                    key,
                    kind,
                    domain: this.domain?.key || '',
                };
            }
            else if (kind === DomainPropertyKind && parent) {
                data.selection = {
                    key: parent,
                    kind: DomainEntityKind,
                    domain: this.domain?.key || '',
                };
                data.field = {
                    key,
                    kind,
                    domain: this.domain?.key || '',
                };
            }
            else if (kind === DomainAssociationKind && parent) {
                data.selection = {
                    key: parent,
                    kind: DomainEntityKind,
                    domain: this.domain?.key || '',
                };
                data.field = {
                    key,
                    kind,
                    domain: this.domain?.key || '',
                };
            }
            else {
                return;
            }
            const ev = new CustomEvent('openissue', {
                detail: data,
                bubbles: true,
                composed: true,
            });
            this.dispatchEvent(ev);
            // Events.Intent.startActivity(
            //   {
            //     action: QUICK_API_SCHEMA,
            //     data,
            //   },
            //   this
            // )
        }
        handleAutoFix() {
            this.dispatchEvent(new Event('autofix'));
        }
        render() {
            if (this.report.length === 0) {
                return nothing;
            }
            return html `
      <div class="validation-report-content">
        ${this.#renderFilters()}${this.#renderStatus()}
        <ul class="report">
          ${this.filteredReport.map((validation, i) => this.#renderValidation(validation, i))}
        </ul>
      </div>
    `;
        }
        #renderStatus() {
            const filteredCount = this.filteredReport.length;
            const totalCount = this.report.length;
            return html ` <div class="status">Showing ${filteredCount} of ${totalCount}</div> `;
        }
        #renderFilters() {
            const isErrorVisible = this.visibleSeverities.has('error');
            const isWarningVisible = this.visibleSeverities.has('warning');
            const isInfoVisible = this.visibleSeverities.has('info');
            return html `
      <div class="filters" @click="${this.handleFilterClick}">
        <ui-button-group type="connected" multiple>
          <ui-button
            color="tonal"
            size="xs"
            toggle
            data-severity="error"
            ?selected="${isErrorVisible}"
            ?disabled="${this.errorCount === 0}"
          >
            ${isErrorVisible ? html `<ui-icon slot="icon">check</ui-icon>` : nothing}Errors (${this.errorCount})
          </ui-button>
          <ui-button
            color="tonal"
            size="xs"
            toggle
            data-severity="warning"
            ?selected="${isWarningVisible}"
            ?disabled="${this.warningCount === 0}"
          >
            ${isWarningVisible ? html `<ui-icon slot="icon">check</ui-icon>` : nothing}Warnings (${this.warningCount})
          </ui-button>
          <ui-button
            color="tonal"
            size="xs"
            toggle
            data-severity="info"
            ?selected="${isInfoVisible}"
            ?disabled="${this.infoCount === 0}"
          >
            ${isInfoVisible ? html `<ui-icon slot="icon">check</ui-icon>` : nothing}Notices (${this.infoCount})
          </ui-button>
        </ui-button-group>
        ${this.withAutoFix ? this.#renderAutoFixButton() : nothing}
      </div>
    `;
        }
        #renderAutoFixButton() {
            return html `
      <ui-button color="outlined" @click="${this.handleAutoFix}" title="Fix all auto fixable issues">
        <ui-icon slot="icon">autorenew</ui-icon> Auto fix
      </ui-button>
    `;
        }
        #renderValidation(validation, index) {
            const { message, severity, help } = validation;
            let icon = '';
            switch (severity) {
                case 'warning':
                    icon = 'warning';
                    break;
                case 'error':
                    icon = 'error';
                    break;
                default:
                    icon = 'info';
                    break;
            }
            return html `
      <li class="${severity}">
        <ui-icon class="report-icon">${icon}</ui-icon>
        <div class="report-details">
          <span class="report-message">${message}</span>
          ${help ? html `<span class="report-help">${help}</span>` : ''}
        </div>
        <ui-button color="text" data-index="${index}" @click="${this.handleOpenIssue}">Open</ui-button>
      </li>
    `;
        }
        constructor() {
            super(...arguments);
            __runInitializers(this, _filteredReport_extraInitializers);
        }
    };
})();
/**
 * An element that specializes in displaying a domain validation report.
 * It is used in the context of the domain validation process.
 *
 * The report is generated elsewhere and passed to this element for display.
 *
 * @fires openissue {CustomEvent<SchemaSelectionInfo>} Fired when the user clicks on the "Open" button
 *   of a validation issue.
 *   The detail contains `SchemaSelectionInfo` with the entity/property/association to navigate to.
 * @fires autofix - Fired when the user clicks on the "Auto fix" button.
 */
export default DomainValidationReport;
//# sourceMappingURL=DomainValidationReport.js.map