import { DeesElement, property, html, customElement, type TemplateResult, css, cssManager } from '@design.estate/dees-element';
import * as plugins from '../plugins.js';

declare global {
  interface HTMLElementTagNameMap {
    'sdig-signpad': SignPad;
  }
}

@customElement('sdig-signpad')
export class SignPad extends DeesElement {
  public static demo = () => html`
    <sdig-signpad></sdig-signpad>
  `;


  constructor() {
    super();
  }

  public static styles = [
    cssManager.defaultStyles,
    css`
      :host {
        display: block;
        color: white;
        position: relative;
        max-width: 600px;
        min-height: 200px;
        max-height: 400px;
      }

      .mainbox {
        position: relative;
        min-height: 280px;
      }

      .signline {
        position: absolute;
        bottom: 30%;
        width: 80%;
        left: 10%;
        border-top: 1px dashed ${cssManager.bdTheme('#00000040', '#ffffff20')};
        pointer-events: none;
      }

      canvas {
        filter: ${cssManager.bdTheme('invert(0)', 'invert(1)')};
      }
    `
  ]

  public render(): TemplateResult {
    return html`
      <div class="mainbox">
        <div class="signline"></div>
      </div>
    `;
  }

  public signaturePad: typeof plugins.signaturePad.prototype;
  public async firstUpdated() {
    const domtools = await this.domtoolsPromise;
    const canvas = document.createElement('canvas');
    this.shadowRoot.querySelector('.mainbox').appendChild(canvas);
    await this.resizeCanvas();
    this.signaturePad = new plugins.signaturePad(canvas, {
      
    });
    this.signaturePad.on();
  }

  public async resizeCanvas() {
    const mainbox = this.shadowRoot.querySelector('.mainbox');
    const mainboxWidth = mainbox.clientWidth;
    const mainboxHeight = mainbox.clientHeight;
    const canvas = this.shadowRoot.querySelector('canvas');
    canvas.width = mainboxWidth;
    canvas.height = mainboxHeight;
    if (this.signaturePad) {
      this.signaturePad.clear();
    }
  }

  public async clear() {
    this.signaturePad.clear();
  }

  public async toData() {
    const returnData =  this.signaturePad.toData();
    return returnData;
  }

  public async fromData(dataArrayArg: any[]) {
    this.signaturePad.fromData(dataArrayArg);
  }

  public async toSVG() {
    return this.signaturePad.toSVG({
      includeBackgroundColor: false,
    });
  }

  public async undo() {
    const data = await this.toData();
    data.pop();
    await this.fromData(data);
  }
}