import { html, TemplateResult } from 'lit'
import { IServer } from '@api-client/core/models/Server.js'
import { DemoPage } from '../../../src/demo/DemoPage.js'
import { reactive } from '../../../src/decorators/index.js'
import ServerEditor from '../../../src/elements/environment/ServerEditor.js'
import '../../../src/define/environment/server-editor.js'

const storeKey = 'api-client.demo.elements.environment.server-editor'

class ComponentDemoPage extends DemoPage {
  override accessor componentName = 'Server editor'

  @reactive() accessor server: IServer | undefined

  constructor() {
    super()
    this.restoreValues()
  }

  restoreValues(): void {
    const data = localStorage.getItem(storeKey)
    if (!data) {
      return
    }
    try {
      this.server = JSON.parse(data) as IServer
    } catch {
      // ...
    }
  }

  storeValues(): void {
    const { server } = this
    if (!server) {
      localStorage.removeItem(storeKey)
    } else {
      localStorage.setItem(storeKey, JSON.stringify(server))
    }
  }

  _changedHandler(): void {
    console.log('change')
    const editor = document.querySelector('server-editor') as ServerEditor
    this.server = editor.getSchema()
    this.storeValues()
  }

  contentTemplate(): TemplateResult {
    const { server } = this
    const { uri, basePath, description, protocol } = server || {}
    return html`
      <a href="./">Back</a>
      <section class="demo-section">
        <server-editor
          .uri="${uri}"
          .basePath="${basePath}"
          .description="${description}"
          .protocol="${protocol}"
          @change="${this._changedHandler}"
        ></server-editor>
      </section>
    `
  }
}

const instance = new ComponentDemoPage()
instance.render()
