import { html, TemplateResult } from 'lit';
import { IHttpAssertion } from '@api-client/core/build/browser.js';
import { DemoPage } from '../../../src/pages/demo/DemoPage.js';
import { reactive } from '../../../src/lib/decorators.js';
import type HttpAssertions from '../../../src/elements/http/HttpAssertions.element.js';
import '../../../src/define/http/http-assertions.js';

const MODEL_STORE_KEY = 'demo.request-ui.editor.assertions';

class ComponentDemoPage extends DemoPage {
  componentName = 'HTTP Assertions';

  @reactive() initialized: boolean;

  @reactive() model: IHttpAssertion[] = [];

  constructor() {
    super();
    this.initialized = false;
    this.init();
  }

  async init(): Promise<void> {
    await this.restoreModel();
    this.initialized = true;
  }

  async restoreModel(): Promise<void> {
    const data = localStorage.getItem(MODEL_STORE_KEY);
    if (!data) {
      return;
    }
    try {
      const tmp = JSON.parse(data);
      if (tmp) {
        const model = tmp as IHttpAssertion[];
        this.model = model;
      }
    } catch (e) {
      // 
    }
  }

  storeModel(): void {
    const { model } = this;
    localStorage.setItem(MODEL_STORE_KEY, JSON.stringify(model));
  }

  handleModelChange(e: Event): void {
    const node = e.target as HttpAssertions;
    const { model = [] } = node;
    this.model = model;
    this.storeModel();
    console.log('model changed', model);
  }

  contentTemplate(): TemplateResult {
    if (!this.initialized) {
      return this.renderLoader();
    }
    return this.renderDemo();
  }

  renderLoader(): TemplateResult {
    return html`
    <a href="./">Back</a>
    <div class="screen-loader">
      <p>Loading demo page</p>
      <progress></progress>
    </div>
    `;
  }

  renderDemo(): TemplateResult {
    return html`
    <a href="./">Back</a>
    <section class="demo-section">
      <h2 class="title-large">HTTP assertions editor</h2>

      <div class="editor-wrapper surface1">
        <http-assertions 
          .model="${this.model}"
          @change="${this.handleModelChange}"
        ></http-assertions>
      </div>
    </section>
    `;
  }
}

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