import { LitElement, PropertyValues } from 'lit'
import { property } from 'lit/decorators.js'
import type { ApiModel } from '@api-client/core/browser.js'

/**
 * A base class for API modeling screens.
 */
export abstract class ApiModelingScreen extends LitElement {
  /**
   * The API model being edited.
   */
  @property({ type: Object }) accessor model: ApiModel | undefined

  constructor() {
    super()
    this.handleDomainChange = this.handleDomainChange.bind(this)
  }

  protected override willUpdate(cp: PropertyValues<this>): void {
    if (cp.has('model')) {
      const old = cp.get('model')
      if (old) {
        old.removeEventListener('change', this.handleDomainChange)
      }
      this.model?.addEventListener('change', this.handleDomainChange)
      this.handleModelChange(this.model)
    }
    super.willUpdate(cp)
  }

  /**
   * A handler for the model change events.
   */
  protected handleDomainChange(): void {
    this.requestUpdate()
  }

  /**
   * Called when the model was set.
   * @param model When set, the model that was set on the element.
   */
  protected abstract handleModelChange(model: ApiModel | undefined): void
}
