import {
  AfterViewInit,
  Component,
  ElementRef, EventEmitter,
  Input,
  OnChanges,
  OnDestroy,
  OnInit, Output,
  ViewChild
} from '@angular/core';

declare global {
  interface Window {
    FBOARD: any;
    FormulaBoard: any;
    __initfp__: any;
    __tmp_fp_input_model__: any;
  }
}

@Component({
  selector: 'app-formula-input',
  templateUrl: './formula-input.component.html',
  styleUrls: ['./formula-input.component.scss']
})

export class FormulaInputComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit {

  @ViewChild('inputEl', {static: true }) inputEl: ElementRef;
  // @ViewChild('wrapperEl', {static: true }) wrapperEl: ElementRef;
  private fboard: any;

  // [(ngModel)]="item.title" (blur)="save()"
  @Input() ngfModel: any;
  @Output() ngfModelChange = new EventEmitter();
  @Output() ngfBlur = new EventEmitter();

  FB_id = 'FormulaBoard';

  constructor() {

  }
  ngOnInit() {

  }
  ngOnChanges() {

  }
  ngOnDestroy(): void {

  }
  valueChanged(evt) {
    console.log('valueChanged', evt);
    this.ngfModelChange.emit(evt);
  }
  showFormulaPad(e) {
    console.log('showFormulaPad', e);
    window.FBOARD.set(e.target.value);
    window.__tmp_fp_input_model__ = this;
    const rect = this.inputEl.nativeElement.getBoundingClientRect();
    const fb = document.getElementById(this.FB_id);
    fb.style.position = 'absolute';
    fb.style.left = rect.left + rect.width + 'px';
    fb.style.top = rect.top + 'px';
    fb.style.visibility = 'visible';
  }
  updateValue(val) {
    this.ngfModel = val;
  }

  ngAfterViewInit() {
    if (window.__initfp__) {
      return;
    }
    window.__initfp__ = true;
    window.FBOARD = new window.FormulaBoard({
      // container: this.wrapperEl.nativeElement,
      id: this.FB_id,
      path: 'assets/formula-board/',
      options: {
        width: 600,
        mode: 'android',
        bottom: false,
      }});

    document.addEventListener('documentMessage', (e) => {
      // @ts-ignore
      if (e.detail.type === 'common.setFormula') {
        // @ts-ignore
        const {formula} = e.detail.data.body;
        console.log(formula);
        window.FBOARD.clear();
        // @ts-ignore
        window.__tmp_fp_input_model__.updateValue(formula);
        const fb = document.getElementById(this.FB_id);
        fb.style.visibility = 'hidden';
      this.ngfBlur.emit();
      }
    });
  }
}

