import { Component, OnInit, EventEmitter, Output, Input } from '@angular/core';
import { WorkflowconfigurationService } from 'src/app/workflowconfiguration/workflowconfiguration/workflowconfiguration.service';
import { ToastrService } from 'ngx-toastr';
declare var $: any;

const options = {
  disableFields: ['button', 'hidden', 'autocomplete', 'date', 'number'],
  disabledActionButtons: ['data', 'save', 'clear'],
  controlOrder: ['text', 'textarea'],
  disabledAttrs: ['access', 'description', 'inline', 'other', 'rows', 'step', 'style', 'toggle'],
  typeUserDisabledAttrs: {
    'text': ['subtype']
  }
};

@Component({
  selector: 'app-fbeditor',
  templateUrl: './fbeditor.component.html',
  styleUrls: ['./fbeditor.component.css']
})
export class FbeditorComponent implements OnInit {
  public fbEditor: any; public formBuilder: any; public formElementJson: any;
  @Output() frmElementJson = new EventEmitter<any>();
  @Input() wfdid: number;
  editOptions: any;
  constructor(
    private workflowconfigurationService: WorkflowconfigurationService,
    private toastr: ToastrService
  ) { }

  ngOnInit(): void {
    this.formElementJson = '';
    this.fbEditor = $(document.getElementById('fb-editor'));
    const input = [];
    input.push({ wfdid: this.wfdid });
    this.workflowconfigurationService.GetByWfdId(input[0]).subscribe(res => {
      if (res.body !== undefined && res.body !== null && res.body[0] !== undefined && res.body[0] !== null) {
        if (JSON.parse(res.body[0]).length > 0) {
          let result: any;
          result = JSON.parse(res.body[0]);
          if (result[0].workflowmetafields !== undefined && result[0].workflowmetafields !== null
            && result[0].workflowmetafields.length > 0) {
            this.setValue(JSON.stringify(result[0].workflowmetafields));
            this.formBuilder = $(this.fbEditor).formBuilder(this.editOptions);
          } else {
            this.formBuilder = $(this.fbEditor).formBuilder(options);
          }
        }
      }
    }, err => { this.toastr.error(err); });
  }
  getValue() {
    this.formElementJson = this.formBuilder.formData;
    this.frmElementJson.emit(this.formElementJson);
  }
  setValue(htmldata) {
    this.editOptions = {
      disableFields: ['button', 'hidden', 'autocomplete', 'date', 'number'],
      disabledActionButtons: ['data', 'save', 'clear'],
      controlOrder: ['text', 'textarea'],
      disabledAttrs: ['access', 'description', 'inline', 'other', 'rows', 'step', 'style', 'toggle'],
      typeUserDisabledAttrs: {
        'text': ['subtype']
      },
      dataType: 'json',
      formData: htmldata
    };
  }
}
