import { Component, OnInit, EventEmitter, Output, Input } from '@angular/core';
import { WorkflowconfigurationService } from 'src/app/workflowconfiguration/workflowconfiguration/workflowconfiguration.service';
import { ToastrService } from 'ngx-toastr';
import {SmartchartService} from './smartchart.service';
import { NgxSpinnerService } from 'ngx-spinner';
require('formBuilder');
require('formBuilder/dist/form-render.min.js');
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']
  }
};*/
var options = {
  showActionButtons: false,
  disableFields: ['button', 'autocomplete', 'hidden','file','checkbox-group','radio-group'],
  onOpenFieldEdit: function (editPanel) {
    var test = editPanel.getElementsByClassName('form-elements form-group label-wrap input-wrap');
    // var getByClass = editPanel.getElementsByClassName('fld-label form-control');
    var getByClass = editPanel.getElementsByClassName('fld-description form-control');
    if ((typeof (getByClass) != undefined) || (typeof (getByClass) != null)) {
      if (getByClass[0].value != undefined)
        var fieldValue = getByClass[0].value;
      if (fieldValue == 'Masters') {
        var removeByClass = editPanel.getElementsByClassName('option-actions');
        if ((typeof (removeByClass) != undefined) || (typeof (removeByClass) != null))
          $(removeByClass).remove();
        //hide the help text       
        var hideLabelByClass = editPanel.getElementsByClassName('form-group description-wrap');
        if ((typeof (hideLabelByClass) != undefined) || (typeof (hideLabelByClass) != null))
          hideLabelByClass[0].style.display = 'none';

        var optionsClass = editPanel.getElementsByClassName('form-group field-options');
        if ((typeof (optionsClass) != undefined) || (typeof (optionsClass) != null)) {
          var d = optionsClass[0].getElementsByClassName('option-selected').length;
          if (d > 1)
            optionsClass[0].style.display = 'none';
        }
        //check box group hide inline and toggle class 
        var inlineClass = editPanel.getElementsByClassName('form-group inline-wrap');
        if ((typeof (inlineClass) != undefined) || (typeof (inlineClass) != null)) {
          if (inlineClass[0].children[1].innerText.trim() == "Display checkbox inline") {
            inlineClass[0].children[1].children[0].checked = false;
            inlineClass[0].style.display = 'none';

            //toggle class
            var toggleClass = editPanel.getElementsByClassName('form-group toggle-wrap');
            if ((typeof (toggleClass) != undefined) || (typeof (toggleClass) != null)) {
              toggleClass[0].style.display = 'none';
            }
          }
        }

        //multiple options       
        var multipleClass = editPanel.getElementsByClassName('form-group multiple-wrap');
        if ((typeof (multipleClass) != undefined) || (typeof (multipleClass) != null))
          if (multipleClass.length != 0)
            multipleClass[0].style.display = 'none';

      }
    }
  },
  onCloseFieldEdit: function (editPanel) {
    var domLabelByClass = editPanel.getElementsByClassName('form-group label-wrap');
    var tableElement = domLabelByClass[0].getElementsByClassName('fld-label form-control');
    if ((typeof (tableElement) != undefined) || (typeof (tableElement) != null)) {
      if (tableElement[0].innerText != undefined)
        var fieldLabel = tableElement[0].innerText;
      if ($(tableElement).find('table').length) {
        var _table = tableElement[0].getElementsByTagName('table');
        var Cells = tableElement[0].getElementsByTagName('td');
        var labelText = Cells[0].innerText;
        //to remove the table element from label content
        if ((typeof (_table) != undefined) || (typeof (_table) != null))
          $(_table).remove();
        $(tableElement).html(labelText);
      }
    }
    var getByClass = editPanel.getElementsByClassName('fld-description form-control');
    if ((typeof (getByClass) != undefined) || (typeof (getByClass) != null)) {
      if (getByClass[0].value != undefined)
        var fieldValue = getByClass[0].value;
      if (fieldValue == 'Masters') {
        //console.log(editPanel.parentElement);
        var parentClass = editPanel.parentElement.getElementsByClassName('checkbox-group')[0];
        if ((typeof (parentClass) != undefined) || (typeof (parentClass) != null)) {
          var g = parentClass.getElementsByClassName('fb-checkbox');
          if ((g != undefined) && (g.length > 0)) {
            var i; var state = "radio";
            for (i = 0; i < g.length; i++) {
              g[i].children[0].type = state;
            }
            event.stopPropagation();
          }
        }
        //check box group
        var inlineClass = editPanel.getElementsByClassName('form-group inline-wrap');
        if ((typeof (inlineClass) != undefined) || (typeof (inlineClass) != null)) {
          if (inlineClass[0].children[1].innerText.trim() == "Display checkbox inline") {
            inlineClass[0].children[1].children[0].checked = false;
            inlineClass[0].style.display = 'none';
          }
        }
      }

    }
  },
  disabledAttrs: [
    'name',
    //"className",
    "access", "subtype", "maxlength", "step", "max", "min"//, "value"
    , 'placeholder',
    , "other"
  ],
  typeUserEvents: {
    select: {
      onadd: function (fld) {
        var tooltipClass = fld.getElementsByClassName('tooltip-element');
        var tooltipValue = tooltipClass[0].attributes.tooltip.value;
        if ((typeof (tooltipClass) != undefined) || (typeof (tooltipClass) != null)) {
          if (tooltipValue == 'Masters') {
            tooltipClass[0].style.display = 'none';
          }
        }
        $('.fld-multiple', fld).change(function (e) {
          var getByClass = fld.getElementsByClassName('fld-description form-control');
          var fieldValue = '';
          if ((typeof (getByClass) != undefined) || (typeof (getByClass) != null)) {
            if (getByClass[0].value != undefined)
              fieldValue = getByClass[0].value;
          }
          var state = "radio";
          var t = e.target.checked ? "checkbox" : "radio";
          if (((t == "checkbox") || (t == "radio")) && (fieldValue == 'Masters')) {
            var d = fld.getElementsByClassName('option-selected');
            if ((d != undefined) && (d.length > 0)) {
              var i;
              for (i = 0; i < d.length; i++) {
                d[i].type = state;
              }
              event.stopPropagation();
            }
          }
        });


      }
    },
    'checkbox-group': {
      onadd: function (fld) {
        var tooltipClass = fld.getElementsByClassName('tooltip-element');
        var tooltipValue = tooltipClass[0].attributes.tooltip.value;
        if ((typeof (tooltipClass) != undefined) || (typeof (tooltipClass) != null)) {
          if (tooltipValue == 'Masters') {
            var state = "radio";
            var d = fld.getElementsByClassName('option-selected');
            if ((d != undefined) && (d.length > 0)) {
              var i;
              for (i = 0; i < d.length; i++) {
                d[i].type = state;
              }
            }
            var g = fld.getElementsByClassName('fb-checkbox');
            if ((g != undefined) && (g.length > 0)) {
              var i;
              for (i = 0; i < g.length; i++) {
                g[i].children[0].type = state;
                $(g[i].children[0]).click(function (e) {
                  //console.log(e);
                });
              }
            }
            tooltipClass[0].style.display = 'none';
          }
        }
      },



    },
    'radio-group': {
      onadd: function (fld) {
        var tooltipClass = fld.getElementsByClassName('tooltip-element');
        var tooltipValue = tooltipClass[0].attributes.tooltip.value;
        if ((typeof (tooltipClass) != undefined) || (typeof (tooltipClass) != null)) {
          if (tooltipValue == 'Masters') {
            tooltipClass[0].style.display = 'none';
          }
        }
      }
    }
  },
  fields: [
    {
      label: 'Predefined dropdown list',
      attrs: {
        type: 'select'
      },
      values: [],
      description: 'Masters',
      icon: '@',
    },
    /*{
      label: 'Predefined Checkbox list',
      attrs: {
        type: 'checkbox-group'
      },
      values: [],
      description: 'Masters',
      icon: '@',
    },
    {
      type: "checkbox-group",
      label: "Checkbox",
      description: 'Masters',
      values: [{ label: "Option 1", value: "1" }],
      icon: "?"

    },
    {
      label: 'Predefined radio button list',
      attrs: {
        type: 'radio-group'
      },
      values: [],
      // disabledFieldButtons: ['edit'],    
      description: 'Masters',
      icon: '@'
    }*/
  ]

};

@Component({
  selector: 'app-smartchart',
  templateUrl: './smartchart.component.html',
  styleUrls: ['./smartchart.component.css']
})
export class SmartchartComponent implements OnInit {
  public fbEditor: any; 
  public formBuilder: any; 
  public formElementJson: any;
   btnName: string; _masterList: any; Options: any; ddlValues = [];
  @Output() frmElementJson = new EventEmitter<any>();
 // @Input() smartchartconfigid: number;
  @Input() buttonName: string;
  @Input() smartChartButtonDisabled: boolean;
  editOptions: any;
  
  constructor(
    private workflowconfigurationService: WorkflowconfigurationService,
    private toastr: ToastrService,
    private smartchartService: SmartchartService,
    private SpinnerService: NgxSpinnerService
  ) { }

  

  ngOnInit() {
    this.SpinnerService.show();
    this.formElementJson = '';
   // console.log(this.buttonName);
    this.fbEditor = $(document.getElementById('fb-editor'));
    if ((this._masterList === undefined) || (this._masterList.length === 0)) {
      this.smartchartService.getMasterTable().subscribe
        ((res) => {
          this._masterList = res;
          if (this._masterList.length !== 0) {
            this._masterList.forEach((i, index) => {
              if (i.masterid != undefined) {
                this.ddlValues.push({
                  'label': i.mastername,
                  'value': i.masterid,
                  //'selected': (index == 0 ? true : false)
                });
              }
            });
            options.fields[0].values = this.ddlValues;
           // options.fields[1].values = this.ddlValues;
          //  options.fields[3].values = this.ddlValues;
          this.formBuilder = $(this.fbEditor).formBuilder(options);
          this.SpinnerService.hide();
          }
        }, err =>{this.SpinnerService.hide();});
    }
    this.btnName = this.buttonName;
    /*if ((this.smartchartconfigid > 0) && (this.btnName === 'Edit')) {
      const input = [];
      input.push({ smartchartconfigid: this.smartchartconfigid });
      this.smartchartService.getByID(input[0]).subscribe(res=> {
          console.log(res);
          if(res.body !== undefined && res.body !== null && res.body.length > 0) {
            let  htmlData = res.body[0].htmldata;
            this.setValue(htmlData);
           // this.formBuilder = $(this.fbEditor).formBuilder(options);
          } else {
            this.formBuilder = $(this.fbEditor).formBuilder(options);
          }          
        });
    } else {
      this.formBuilder = $(this.fbEditor).formBuilder(options);
    }*/
  }

  getValue() {
    this.formElementJson = this.formBuilder.formData;   
    this.frmElementJson.emit(this.formElementJson);
  }

 

  setValue(htmldata) {
   this.SpinnerService.show();       
   console.log(htmldata);
   this._masterList = [];
    var  options1 = {
        showActionButtons: false,
        disableFields: ['button', 'autocomplete', 'hidden' , 'file','checkbox-group','radio-group'],
        onOpenFieldEdit: function (editPanel) {
          var test = editPanel.getElementsByClassName('form-elements form-group label-wrap input-wrap');
          // var getByClass = editPanel.getElementsByClassName('fld-label form-control');
          var getByClass = editPanel.getElementsByClassName('fld-description form-control');
          if ((typeof (getByClass) != undefined) || (typeof (getByClass) != null)) {
            if (getByClass[0].value != undefined)
              //  var fieldLabel = getByClass[0].innerText; 
              var fieldValue = getByClass[0].value;
            //  if ((fieldLabel == 'Predefined dropdown list') || (fieldLabel == 'Checkbox') || (fieldLabel == 'Predefined radio button list')) {

            var chkOptionsClass = editPanel.getElementsByClassName('form-group field-options');
            if (fieldValue == 'Masters') {
              var removeByClass = editPanel.getElementsByClassName('option-actions');
              if ((typeof (removeByClass) != undefined) || (typeof (removeByClass) != null))
                $(removeByClass).remove();
              //hide the help text       
              var hideLabelByClass = editPanel.getElementsByClassName('form-group description-wrap');
              if ((typeof (hideLabelByClass) != undefined) || (typeof (hideLabelByClass) != null))
                hideLabelByClass[0].style.display = 'none';

              var optionsClass = editPanel.getElementsByClassName('form-group field-options');
              if ((typeof (optionsClass) != undefined) || (typeof (optionsClass) != null)) {
                var d = optionsClass[0].getElementsByClassName('option-selected').length;
                if (d > 1)
                  optionsClass[0].style.display = 'none';
              }
              //check box group hide inline and toggle class 
              var inlineClass = editPanel.getElementsByClassName('form-group inline-wrap');
              if ((typeof (inlineClass) != undefined) || (typeof (inlineClass) != null)) {
                if (inlineClass[0].children[1].innerText.trim() == "Display checkbox inline") {
                  inlineClass[0].children[1].children[0].checked = false;
                  inlineClass[0].style.display = 'none';

                  //toggle class
                  var toggleClass = editPanel.getElementsByClassName('form-group toggle-wrap');
                  if ((typeof (toggleClass) != undefined) || (typeof (toggleClass) != null)) {
                    toggleClass[0].style.display = 'none';
                  }
                }
              }

              //multiple options       
              var multipleClass = editPanel.getElementsByClassName('form-group multiple-wrap');
              if ((typeof (multipleClass) != undefined) || (typeof (multipleClass) != null))
                multipleClass[0].style.display = 'none';

            }
          }
        },
        onCloseFieldEdit: function (editPanel) {
          var domLabelByClass = editPanel.getElementsByClassName('form-group label-wrap');
          var tableElement = domLabelByClass[0].getElementsByClassName('fld-label form-control');
          if ((typeof (tableElement) != undefined) || (typeof (tableElement) != null)) {
            if (tableElement[0].innerText != undefined)
              var fieldLabel = tableElement[0].innerText;
            if ($(tableElement).find('table').length) {
              var _table = tableElement[0].getElementsByTagName('table');
              var Cells = tableElement[0].getElementsByTagName('td');
              var labelText = Cells[0].innerText;
              //to remove the table element from label content
              if ((typeof (_table) != undefined) || (typeof (_table) != null))
                $(_table).remove();
              $(tableElement).html(labelText);
            }
          }
          var getByClass = editPanel.getElementsByClassName('fld-description form-control');
          if ((typeof (getByClass) != undefined) || (typeof (getByClass) != null)) {
            if (getByClass[0].value != undefined)
              var fieldValue = getByClass[0].value;
            if (fieldValue == 'Masters') {
              //console.log(editPanel.parentElement);
              var parentClass = editPanel.parentElement.getElementsByClassName('checkbox-group')[0];
              if ((typeof (parentClass) != undefined) || (typeof (parentClass) != null)) {
                var g = parentClass.getElementsByClassName('fb-checkbox');
                if ((g != undefined) && (g.length > 0)) {
                  var i; var state = "radio";
                  for (i = 0; i < g.length; i++) {
                    g[i].children[0].type = state;
                  }
                  event.stopPropagation();
                }
              }

              //check box group
              var inlineClass = editPanel.getElementsByClassName('form-group inline-wrap');
              if ((typeof (inlineClass) != undefined) || (typeof (inlineClass) != null)) {
                if (inlineClass[0].children[1].innerText.trim() == "Display checkbox inline") {
                  inlineClass[0].children[1].children[0].checked = false;
                  inlineClass[0].style.display = 'none';
                }
              }
            }

          }
        },
        disabledAttrs: [
          'name',
          //"className",
          "access", "subtype", "maxlength", "step", "max", "min"//, "value"
          , 'placeholder',
          , "other"
        ],
        typeUserEvents: {
          select: {
            onadd: function (fld) {
              var tooltipClass = fld.getElementsByClassName('tooltip-element');
              var tooltipValue = tooltipClass[0].attributes.tooltip.value;
              if ((typeof (tooltipClass) != undefined) || (typeof (tooltipClass) != null)) {
                if (tooltipValue == 'Masters') {
                  tooltipClass[0].style.display = 'none';
                }
              }
              $('.fld-multiple', fld).change(function (e) {
                var getByClass = fld.getElementsByClassName('fld-description form-control');
                var fieldValue = '';
                if ((typeof (getByClass) != undefined) || (typeof (getByClass) != null)) {
                  if (getByClass[0].value != undefined)
                    fieldValue = getByClass[0].value;
                }
                var state = "radio";
                var t = e.target.checked ? "checkbox" : "radio";
                if (((t == "checkbox") || (t == "radio")) && (fieldValue == 'Masters')) {
                  var d = fld.getElementsByClassName('option-selected');
                  if ((d != undefined) && (d.length > 0)) {
                    var i;
                    for (i = 0; i < d.length; i++) {
                      d[i].type = state;
                    }
                    event.stopPropagation();
                  }
                }
              });
            }
          },
          'checkbox-group': {
            onadd: function (fld) {
              var tooltipClass = fld.getElementsByClassName('tooltip-element');
              var tooltipValue = tooltipClass[0].attributes.tooltip.value;
              if ((typeof (tooltipClass) != undefined) || (typeof (tooltipClass) != null)) {
                if (tooltipValue == 'Masters') {
                  var state = "radio";
                  var d = fld.getElementsByClassName('option-selected');
                  if ((d != undefined) && (d.length > 0)) {
                    var i;
                    for (i = 0; i < d.length; i++) {
                      d[i].type = state;
                    }
                  }
                  var g = fld.getElementsByClassName('fb-checkbox');
                  if ((g != undefined) && (g.length > 0)) {
                    var i;
                    for (i = 0; i < g.length; i++) {
                      g[i].children[0].setAttribute('onclick', function () {
                        //console.log('test');
                      })
                      $(g[i]).click(function (e) {
                        var chk = fld.getElementsByClassName('fb-checkbox');
                        var h;
                        for (h = 0; h < chk.length; h++) {
                          chk[h].children[0].checked = false;
                        }
                        e.currentTarget.children[0].checked = true
                      });

                    }
                  }
                  tooltipClass[0].style.display = 'none';

                }
              }
            }

          },
          'radio-group': {
            onadd: function (fld) {
              var tooltipClass = fld.getElementsByClassName('tooltip-element');
              var tooltipValue = tooltipClass[0].attributes.tooltip.value;
              if ((typeof (tooltipClass) != undefined) || (typeof (tooltipClass) != null)) {
                if (tooltipValue == 'Masters') {
                  tooltipClass[0].style.display = 'none';
                }
              }
            }
          }
        },        
  fields: [
    {
      label: 'Predefined dropdown list',
      attrs: {
        type: 'select'
      },
      values: [],
      description: 'Masters',
      icon: '@',
    },
    /*{
      label: 'Predefined Checkbox list',
      attrs: {
        type: 'checkbox-group'
      },
      values: [],
      description: 'Masters',
      icon: '@',
    },
    {
      type: "checkbox-group",
      label: "Checkbox",
      description: 'Masters',
      values: [{ label: "Option 1", value: "1" }],
      icon: "?"

    },
    {
      label: 'Predefined radio button list',
      attrs: {
        type: 'radio-group'
      },
      values: [],
      // disabledFieldButtons: ['edit'],    
      description: 'Masters',
      icon: '@'
    }*/
  ],
        dataType: 'json',
        formData: htmldata
      };    
    if ((this._masterList === undefined) || (this._masterList.length === 0)) {
      this.smartchartService.getMasterTable().subscribe
        ((res) => {
          this._masterList = []; this.ddlValues = [];
          this._masterList = res;
          if (this._masterList.length !== 0) {
            this._masterList.forEach((i, index) => {
              if (i.masterid !== undefined) {
                this.ddlValues.push({
                  'label': i.mastername,
                  'value': i.masterid                   
                });
              }
            });
            options1.fields[0].values = this.ddlValues;
           // options1.fields[1].values = this.ddlValues;
           // options1.fields[3].values = this.ddlValues; 
            let getByClass = $(document.getElementsByClassName('form-wrap form-builder'));
          let fbTemplate = $(document.getElementById('fb-editor'));
            if ((typeof (getByClass) !== undefined) || (typeof (getByClass) !== null) )
              $(getByClass).remove();    
             $(fbTemplate).formBuilder(options1);  
             this.SpinnerService.hide();
          }
        }, err => {this.SpinnerService.hide();});    
  } 
  //this.SpinnerService.hide();
  }







  clearBuilder() {
    this.SpinnerService.show();
    var getByClass = $(document.getElementsByClassName('form-wrap form-builder'));
    var fbTemplate = $(document.getElementById('fb-editor'));
    if ((typeof (getByClass) != undefined) || (typeof (getByClass) != null))
      $(getByClass).remove();
    $(fbTemplate).formBuilder(options); 
    this.SpinnerService.hide();    
  }
}
