import { __esDecorate, __runInitializers } from "tslib";
import { DEFAULT_SKU_CONFIG } from '@api-client/core/modeling/definitions/SKU.js';
import { TaxonomyDialog } from './TaxonomyDialog.js';
import { SemanticType } from '@api-client/core/modeling/Semantics.js';
import { bound } from '../../decorators/bound.js';
import { html, nothing } from 'lit';
import { renderHelp } from '../../help/render.js';
import { repeat } from 'lit/directives/repeat.js';
import '../../md/divider/ui-divider.js';
let SkuTaxonomy = (() => {
    let _classSuper = TaxonomyDialog;
    let _instanceExtraInitializers = [];
    let _handleCustomPatternChange_decorators;
    let _handleReservedValuesChange_decorators;
    let _handleRemoveReservedValue_decorators;
    let _render_decorators;
    return class SkuTaxonomy extends _classSuper {
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _handleCustomPatternChange_decorators = [bound];
            _handleReservedValuesChange_decorators = [bound];
            _handleRemoveReservedValue_decorators = [bound];
            _render_decorators = [bound];
            __esDecorate(this, null, _handleCustomPatternChange_decorators, { kind: "method", name: "handleCustomPatternChange", static: false, private: false, access: { has: obj => "handleCustomPatternChange" in obj, get: obj => obj.handleCustomPatternChange }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate(this, null, _handleReservedValuesChange_decorators, { kind: "method", name: "handleReservedValuesChange", static: false, private: false, access: { has: obj => "handleReservedValuesChange" in obj, get: obj => obj.handleReservedValuesChange }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate(this, null, _handleRemoveReservedValue_decorators, { kind: "method", name: "handleRemoveReservedValue", static: false, private: false, access: { has: obj => "handleRemoveReservedValue" in obj, get: obj => obj.handleRemoveReservedValue }, metadata: _metadata }, null, _instanceExtraInitializers);
            __esDecorate(this, null, _render_decorators, { kind: "method", name: "render", static: false, private: false, access: { has: obj => "render" in obj, get: obj => obj.render }, metadata: _metadata }, null, _instanceExtraInitializers);
            if (_metadata) Object.defineProperty(this, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        domainElement = __runInitializers(this, _instanceExtraInitializers);
        static title = `Configure SKU Taxonomy`;
        /**
         * The list of properties available for source list.
         * It is a computed list for the parent entity and all its parents.
         */
        properties = [];
        constructor(domainElement) {
            let config;
            const semantic = domainElement.semantics.find((s) => s.id === SemanticType.SKU);
            if (semantic && semantic.config) {
                config = structuredClone(semantic.config);
            }
            else {
                config = {};
            }
            super(config);
            this.domainElement = domainElement;
            const entity = domainElement.getParentInstance();
            if (entity) {
                this.properties = this.listComputedProperties(entity, {
                    exclude: [this.domainElement.key],
                    types: ['string', 'number'],
                });
            }
        }
        formCallback(event) {
            const semantic = this.domainElement.semantics.find((s) => s.id === SemanticType.SKU);
            if (semantic) {
                semantic.config = this.config;
            }
            else {
                this.domainElement.semantics.push({
                    id: SemanticType.SKU,
                    config: this.config,
                });
            }
            this.domainElement.domain.notifyChange();
            return super.formCallback(event);
        }
        handleCustomPatternChange(event) {
            const input = event.target;
            const value = input.value.trim();
            if (!value) {
                delete this.config.customPattern;
            }
            else if (this.isValidRegex(value)) {
                this.config.customPattern = value;
            }
            else {
                input.invalidText = 'Invalid regular expression pattern';
                input.invalid = true;
                return;
            }
            input.invalid = false;
            this.requestUpdate();
        }
        isValidRegex(pattern) {
            try {
                new RegExp(pattern);
                return true;
            }
            catch {
                return false;
            }
        }
        handleReservedValuesChange(event) {
            const input = event.target;
            const value = input.value.trim();
            if (value) {
                const reservedValues = this.config?.reservedValues ?? DEFAULT_SKU_CONFIG.reservedValues ?? [];
                if (!reservedValues.includes(value)) {
                    reservedValues.push(value);
                    this.config = { ...this.config, reservedValues };
                    this.requestUpdate();
                }
                input.value = '';
            }
        }
        handleRemoveReservedValue(event) {
            const chip = event.currentTarget;
            const index = parseInt(chip.dataset.index || '-1', 10);
            if (index >= 0 && this.config?.reservedValues) {
                this.config.reservedValues.splice(index, 1);
                this.requestUpdate();
            }
        }
        render() {
            return html `
      <div class="input-group">
        ${this.renderValidationModeSelect()} ${this.renderCustomPatternInput()} ${this.renderCaseModeSelect()}
        ${this.renderPrefixInput()} ${this.renderReservedValuesInput()}
      </div>
      <div class="checkbox-group">
        ${this.renderEnforceUniqueness()} ${this.renderValidateReservedWords()} ${this.renderAutoGenerate()}
      </div>
      <div class="input-group">${this.renderAutoGenerateSourceSelect()}</div>
    `;
        }
        renderValidationModeSelect() {
            const value = this.config?.validationMode ?? DEFAULT_SKU_CONFIG.validationMode;
            return html `
      <div class="row">
        <ui-select
          label="Validation mode"
          class="input"
          name="validationMode"
          .value="${value}"
          @change="${this.handleSelectChange}"
        >
          <ui-option value="strict">Strict</ui-option>
          <ui-option value="lenient">Lenient</ui-option>
          <ui-option value="custom">Custom</ui-option>
        </ui-select>
        ${renderHelp('taxonomy', 'sku:validationMode')}
      </div>
    `;
        }
        renderCustomPatternInput() {
            const mode = this.config?.validationMode ?? DEFAULT_SKU_CONFIG.validationMode;
            if (mode !== 'custom') {
                return nothing;
            }
            const value = this.config?.customPattern ?? DEFAULT_SKU_CONFIG.customPattern;
            return html `
      <div class="row input-row">
        <ui-outlined-text-field
          label="Custom Pattern"
          class="input"
          name="customPattern"
          .value="${value}"
          @change="${this.handleCustomPatternChange}"
          required
        ></ui-outlined-text-field>
        ${renderHelp('taxonomy', 'sku:customPattern')}
      </div>
    `;
        }
        renderCaseModeSelect() {
            const value = this.config?.caseMode ?? DEFAULT_SKU_CONFIG.caseMode;
            return html `
      <div class="row input-row">
        <ui-select
          label="Case Mode"
          class="input"
          name="caseMode"
          .value="${value}"
          @change="${this.handleSelectChange}"
        >
          <ui-option value="uppercase">Uppercase</ui-option>
          <ui-option value="lowercase">Lowercase</ui-option>
          <ui-option value="preserve">Preserve Case</ui-option>
        </ui-select>
        ${renderHelp('taxonomy', 'sku:caseMode')}
      </div>
    `;
        }
        renderPrefixInput() {
            const value = this.config?.prefix ?? DEFAULT_SKU_CONFIG.prefix;
            return html `
      <div class="row input-row">
        <ui-outlined-text-field
          label="Prefix"
          class="input"
          name="prefix"
          .value="${value}"
          @change="${this.handleTextChange}"
        ></ui-outlined-text-field>
        ${renderHelp('taxonomy', 'sku:prefix')}
      </div>
    `;
        }
        renderReservedValuesInput() {
            const value = this.config?.reservedValues ?? DEFAULT_SKU_CONFIG.reservedValues;
            const chips = (value || []).map((val, index) => html `<ui-chip type="input" removable data-index="${index}" @remove="${this.handleRemoveReservedValue}"
          >${val}</ui-chip
        >`);
            return html `
      <div class="row input-row">
        <div class="input chips-input">
          <ui-outlined-text-field
            class="input"
            name="reservedValues"
            label="Reserved Values"
            @change="${this.handleReservedValuesChange}"
            supportingText="Add a reserved value and press Enter to add it to the list."
          ></ui-outlined-text-field>
          <ui-chip-set>${chips}</ui-chip-set>
        </div>
        ${renderHelp('taxonomy', 'sku:reservedValues')}
      </div>
    `;
        }
        renderEnforceUniqueness() {
            const value = this.config?.enforceUniqueness ?? DEFAULT_SKU_CONFIG.enforceUniqueness;
            return html `
      <div class="row">
        <div class="input checkbox metadata">
          <ui-checkbox
            id="enforce-uniqueness"
            name="enforceUniqueness"
            .checked="${value}"
            @change="${this.handleBooleanChange}"
          ></ui-checkbox>
          <div class="label">
            <label for="enforce-uniqueness" class="body-medium">Enforce Uniqueness</label>
            <span class="body-small meta">Whether to enforce global uniqueness across all entities.</span>
          </div>
        </div>
        ${renderHelp('taxonomy', 'sku:enforceUniqueness')}
      </div>
    `;
        }
        renderValidateReservedWords() {
            const value = this.config?.validateReservedWords ?? DEFAULT_SKU_CONFIG.validateReservedWords;
            return html `
      <div class="row">
        <div class="input checkbox metadata">
          <ui-checkbox
            id="validate-reserved-words"
            name="validateReservedWords"
            .checked="${value}"
            @change="${this.handleBooleanChange}"
          ></ui-checkbox>
          <div class="label">
            <label for="validate-reserved-words" class="body-medium">Validate Reserved Words</label>
            <span class="body-small meta">Whether to validate against reserved words.</span>
          </div>
        </div>
        ${renderHelp('taxonomy', 'sku:validateReservedWords')}
      </div>
    `;
        }
        renderAutoGenerate() {
            const value = this.config?.autoGenerate ?? DEFAULT_SKU_CONFIG.autoGenerate;
            return html `
      <div class="row">
        <div class="input checkbox metadata">
          <ui-checkbox
            id="auto-generate"
            name="autoGenerate"
            .checked="${value}"
            @change="${this.handleBooleanChange}"
          ></ui-checkbox>
          <div class="label">
            <label for="auto-generate" class="body-medium">Auto Generate</label>
            <span class="body-small meta">Whether to auto-generate SKUs for new entities.</span>
          </div>
        </div>
        ${renderHelp('taxonomy', 'sku:autoGenerate')}
      </div>
    `;
        }
        renderAutoGenerateSourceSelect() {
            const autoGenerate = this.config?.autoGenerate ?? DEFAULT_SKU_CONFIG.autoGenerate;
            if (!autoGenerate) {
                return nothing;
            }
            const value = this.config?.autoGenerateSource ?? DEFAULT_SKU_CONFIG.autoGenerateSource;
            return html `
      <div class="row input-row">
        <ui-select
          label="Auto Generate Source"
          class="input"
          name="autoGenerateSource"
          .value="${value}"
          @change="${this.handleSelectChange}"
        >
          <ui-option value="">
            <div>Random</div>
            <div slot="supporting-text">Use a randomly generated value.</div>
          </ui-option>
          <ui-divider></ui-divider>
          ${repeat(this.properties, (prop) => prop.key, (prop) => {
                return html `
                <ui-option value="${prop.key}">
                  <div>${prop.info.getLabel()}</div>
                  ${prop.info.description ? html `<div slot="supporting-text">${prop.info.description}</div>` : nothing}
                </ui-option>
              `;
            })}
        </ui-select>
        ${renderHelp('taxonomy', 'sku:autoGenerateSource')}
      </div>
    `;
        }
    };
})();
export { SkuTaxonomy };
//# sourceMappingURL=SkuTaxonomy.js.map