import { attribute, elementDefine, onAttributeChanged } from '../index';
import { SwcHTMLInputElementBase } from '../elements/base/SwcHTMLInputElementBase';

interface Branch { tpl: HTMLElement; test: string | null; }
@elementDefine({ name: 'swc-choose-input', extends: 'input' })
export class SwcChooseInput extends SwcHTMLInputElementBase {
  private _placeholder = document.createComment("swc-choose-placeholder"); private _isShowing = true; private _isInitialized = false; private _observer: MutationObserver | null = null;
  @attribute('swc-value') _swcValue: any = undefined; private _branches: Branch[] = []; private _otherBranch: Branch | null = null; private _branchInit = false;
  @onAttributeChanged('swc-value') onValueChange() { this.evaluate(); }
  set swcValue(val: any) { this._swcValue = val; } get swcValue() { return this._swcValue; }
  connectedCallback() { if (this._isInitialized) return; this._isInitialized = true; this._initBranches(); this._observer = new MutationObserver(() => this.evaluate()); this._observer.observe(this, { attributes: true }); this.evaluate(); }
  private _initBranches() { if (this._branchInit) return; Array.from(this.children).forEach(c => { const isWhen = c.localName === 'swc-when' || c.getAttribute('is')?.startsWith('swc-when-'); const isOther = c.localName === 'swc-other' || c.getAttribute('is')?.startsWith('swc-other-'); const branch: Branch = { tpl: c.cloneNode(true) as HTMLElement, test: c.getAttribute('test') }; if (isWhen) this._branches.push(branch); else if (isOther) this._otherBranch = branch; }); this._branchInit = true; }
  disconnectedCallback() { this._observer?.disconnect(); }
  private evaluate() { let matchedBranch: Branch | null = null; const chooseValue = this.getAttribute('swc-value') ?? this.getAttribute('value') ?? this._swcValue; for (const branch of this._branches) { const testAttr = branch.test; if (testAttr === null || testAttr.includes('{{')) continue; let isMet = false; if (chooseValue !== undefined && chooseValue !== null) { isMet = String(chooseValue) === String(testAttr); } else { try { if (testAttr === 'true') isMet = true; else if (testAttr === 'false') isMet = false; else isMet = !!new Function('return ' + testAttr)(); } catch (e) { isMet = false; } } if (isMet) { matchedBranch = branch; break; } } if (!matchedBranch && this._otherBranch) { matchedBranch = this._otherBranch; } if (!matchedBranch && this._isShowing) { if (this.parentNode) { this.parentNode.insertBefore(this._placeholder, this); this.remove(); this._isShowing = false; } } else if (matchedBranch) { if (!this._isShowing) { if (this._placeholder.parentNode) { this._placeholder.parentNode.insertBefore(this, this._placeholder); this._placeholder.remove(); this._isShowing = true; } } if (this._isShowing) { this.innerHTML = ''; const clone = matchedBranch.tpl.cloneNode(true) as HTMLElement; clone.style.display = 'contents'; this.appendChild(clone); this.applyData(clone, this._swcValue); } } }
}
