import { html, TemplateResult } from 'lit';
import { IProperty, Property } from '@api-client/core/build/browser.js';
import { DemoPage } from '../../../src/pages/demo/DemoPage.js';
import { reactive } from '../../../src/lib/decorators.js';
import env from '../../env.js'
import '../../../src/define/environment/variables-editor.js';
import '../../../src/define/ui/ui-button.js';

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

class ComponentDemoPage extends DemoPage {
  componentName = 'Variables editor';

  @reactive() variables?: IProperty[];

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

  fromEnvironment(): void {
    const result: IProperty[] = [];
    Object.keys(env.systemVariables).forEach((key) => {
      const value = env.systemVariables[key];
      const prop = Property.String(key, String(value));
      result.push(prop.toJSON());
    });
    this.variables = result;
  }

  restoreValues(): void {
    const data = localStorage.getItem(storeKey);
    if (!data) {
      this.fromEnvironment();
      return;
    }
    try {
      const list = JSON.parse(data) as IProperty[];
      if (Array.isArray(list)) {
        this.variables = list;
      } else {
        this.fromEnvironment();
      }
    } catch (e) {
      this.fromEnvironment();
    }
  }

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

  loadSystem(): void {
    this.fromEnvironment();
    this.storeValues();
  }

  _changedHandler(): void {
    console.log('change');
    const editor = document.querySelector('variables-editor')!;
    this.variables = editor.variables;
    this.storeValues();
  }

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

  renderDataControl(): TemplateResult {
    return html`
    <section class="demo-section">
      <h2 class="title-large">Data control</h2>
      <ui-button type="outlined" @click="${this.loadSystem}">Load system variables</ui-button>
    </section>
    `;
  }
}

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