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

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

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

  @reactive() accessor environment: IEnvironment = new Environment().toJSON()

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

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

  _changedHandler(): void {
    const editor = document.querySelector('environment-editor') as EnvironmentEditor
    localStorage.setItem(storeKey, JSON.stringify(editor.environment))
    console.log('change')
  }

  contentTemplate(): TemplateResult {
    return html`
      <a href="./">Back</a>
      <section class="demo-section">
        <environment-editor .environment="${this.environment}" @change="${this._changedHandler}"></environment-editor>
      </section>
    `
  }
}

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