import { Component, OnInit, TemplateRef, Input } from '@angular/core';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap/modal';
import { FormGroup, Validators, FormBuilder, FormArray, FormControl, ValidatorFn } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { MenurightsService } from './menurights.service';
import { DomSanitizer } from '@angular/platform-browser';
import { MenuService } from '../../masters/menu/menu.service';
import * as $ from 'jquery';
declare let $: any;
@Component({
  selector: 'app-menurights',
  templateUrl: './menurights.component.html',
  styleUrls: ['./menurights.component.css']
})
export class MenurightsComponent implements OnInit {
  _mappedMenuActionList = [];
  actions = [];
  actionnew: any = [];
  actionList = [];
  _menuList: any = []; _actionList: any[];
  actionArray = [];
  checkedAll: boolean;
  menurightsForm: FormGroup;
  form: FormGroup;
  childinput: number;
  checkedstatus: boolean;
  usermenumapped: string;
  loading = false;
  parentuserid = 1;
  constructor(
    private router: Router,
    private toastr: ToastrService,
    private menurightsService: MenurightsService,
    private _sanitizer: DomSanitizer,
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private menuService: MenuService

  ) {
    const formControls = this.actions.map(control => new FormControl(false));
    // Create a FormControl for the select/unselect all checkbox
    const selectAllControl = new FormControl(false);
    this.menurightsForm = this.formBuilder.group({
      menumapped: [''],
      selectAll: selectAllControl,
      actions: new FormArray(formControls)

    });
    if (this._menuList.length === 0) {
      this.loadmenu();
    }
  }

  ngOnInit() {
    this.form = this.formBuilder.group({
    });
  }


  ngOnChanges() {
    if (this.parentuserid > 0) {
      this.childinput = this.parentuserid;
    }
    this.menurightsForm.get('selectAll').setValue(false);
  }

  loadmenu() {
    // this.SpinnerService.show();
    this.menurightsService.GetAction().toPromise().then(resaction => {
      if (resaction !== undefined) {
        if (resaction.length > 0) {
          resaction.forEach(item => {
            var data = JSON.parse(item.spgetactionlist);
            this.actions.push(data);
          });

          this.menuService.GetActive().toPromise().then(res => {
            if (res != null && res !== undefined && res[0] !== undefined) {
              if (JSON.parse(res[0]).length > 0) {
                this._menuList = JSON.parse(res[0]);
                this.actions.map((o, i) => {
                  const control = new FormControl(); // if first item set to true, else false
                  (this.menurightsForm.controls.actions as FormArray).push(control);
                });

                var checkedany = 'false';
                for (var value of this._menuList) {
                  if ($('#' + value.menuid).is(':checked')) {
                    checkedany = 'true';
                  } else {
                    checkedany = 'false';
                    break;
                  }
                }

                if (checkedany === 'true') {
                  this.menurightsForm.get('selectAll').setValue(true);
                }
                if (checkedany === 'false') {
                  this.menurightsForm.get('selectAll').setValue(false);
                }
              }
            }
          }, error => {
            // this.SpinnerService.hide();
            this.toastr.error('Error while getting menu data');
          });
        }
      }
      // this.SpinnerService.hide();
    }, error => {
      // this.SpinnerService.hide();
      this.toastr.error('Error while getting action data');
    });
  }

  reset() {
    this.menurightsForm.get('selectAll').setValue(false);
    this._menuList.forEach(item => {
      let e2 = document.getElementById(item.menuid);
      (<HTMLInputElement>e2).checked = false;
      this.actions.forEach(a => {
        if (a.actionid != '') {
          var actionId = '';
          actionId = item.menuid + '_' + a.actionid;
          let e6 = document.getElementById(actionId);
          (<HTMLInputElement>e6).checked = false;
          this.onCheckboxChange(item.menuid, a.actionid, false);
        }
      });
    });
  }

  selectAll(e) {
    this.actionArray = [];
    if (e.currentTarget.checked == true) {
      this._menuList.forEach(item => {
        let e2 = document.getElementById(item.menuid);
        (<HTMLInputElement>e2).checked = true;
        this.actions.forEach(a => {
          if (a.actionid !== '') {
            var actionId = '';
            actionId = item.menuid + '_' + a.actionid;
            if (a.actionid !== 1) {
              let e6 = document.getElementById(actionId);
              (<HTMLInputElement>e6).checked = true;
              // this.onCheckboxChange(item.data.menuid, a.actionid, true);
            } else {
              let e6 = document.getElementById(actionId);
              (<HTMLInputElement>e6).checked = false;

            }
          }
        });
      });
    }

    if (e.currentTarget.checked === false) {
      this._menuList.forEach(item => {
        let e2 = document.getElementById(item.menuid);
        (<HTMLInputElement>e2).checked = false;
        this.actions.forEach(a => {
          if (a.actionid !== '') {
            var actionId = '';
            actionId = item.menuid + '_' + a.actionid;
            let e6 = document.getElementById(actionId);
            (<HTMLInputElement>e6).checked = false;
            // this.onCheckboxChange(item.data.menuid, a.actionid, false);
          }
        });
      });
    }
  }

  getselectedmenus() {
    this._mappedMenuActionList = [];
    this._menuList.forEach(item => {
      var selected = [];
      this.actions.forEach(a => {
        if (a.actionid !== '') {
          var actionId = '';
          actionId = item.menuid + '_' + a.actionid;
          var a1 = document.getElementById(actionId);
          if ($('#' + actionId).is(':checked')) {
            selected.push(a.actionid);
          }
        }
      });

      this._mappedMenuActionList.push({
        'menuid': item.menuid,
        'action': selected
      });

    });

    return this._mappedMenuActionList;

  }
  getselectedmenuscheck() {


    this.checkedstatus = false;
    for (let item of this._menuList) {
      if ($('#' + item.menuid).is(':checked')) {
        this.checkedstatus = true;
        break;
      }
    }
    return this.checkedstatus;
  }
  onMenuChange(id, e) {
    if (e.currentTarget.checked === false) {
      this.menurightsForm.get('selectAll').setValue(false);
      this.actions.forEach(a => {
        if (a.actionid !== '') {
          var actionId = '';
          actionId = id + '_' + a.actionid;
          let e6 = document.getElementById(actionId);

          (<HTMLInputElement>e6).checked = false;
          this.onCheckboxChange(id, a.actionid, false);

        }
      });
    } else {

      let checkedany = 'false';


      for (const value of this._menuList) {
        if ($('#' + value.menuid).is(':checked')) {
          checkedany = 'true';
        } else {
          checkedany = 'false';
          break;
        }
      }

      // this._menuList.forEach(item => {

      // });

      if (checkedany === 'true') {
        this.menurightsForm.get('selectAll').setValue(true);
      }
      this.actions.forEach(a => {
        if (a.actionid !== '') {
          var actionId = '';
          actionId = id + '_' + a.actionid;
          let e6 = document.getElementById(actionId);
          if (a.actionid !== 1) {
            (<HTMLInputElement>e6).checked = true;
            this.onCheckboxChange(id, a.actionid, true);
          }
        }
      });
      // console.log(this.actionArray);
    }

  }
  onCheckboxChange(id, data, isChecked: boolean) {
    if (isChecked) {
      this.actionArray.push({ 'menuid': id, 'action': data });
    } else {
      this.actionArray.splice(this.actionArray.findIndex(e => e.action == data && e.menuid === id
      ), 1);
    }
    this._menuList.forEach(item => {
      var selected = [];
      if (item.menuid == id) {
        let e10 = document.getElementById(item.menuid);
        if (isChecked == true) {
          (<HTMLInputElement>e10).checked = true;
        }
        this.actions.forEach(a => {
          if (a.actionid != '') {
            var actionId = '';
            if (a.actionid == 1) {
              actionId = item.menuid + '_' + a.actionid;
              if (data == a.actionid) {
                if (isChecked == true) {
                  this.actions.forEach(a1 => {
                    if (a1.actionid != 1) {
                      actionId = item.menuid + '_' + a1.actionid;
                      let e6 = document.getElementById(actionId);
                      (<HTMLInputElement>e6).checked = false;
                    }
                  });
                }
                else {
                  (<HTMLInputElement>e10).checked = false;
                }
              }
            }
            else {
              var actionIdreadonly = 'false';
              var actionIdread = '';
              actionId = item.menuid + '_' + a.actionid;
              actionIdread = item.menuid + '_' + 1;
              let e6 = document.getElementById(actionIdread);
              for (var a1 of this.actions) {
                if (a1.actionid != 1) {
                  actionId = item.menuid + '_' + a1.actionid;
                  let e6 = document.getElementById(actionId);
                  if ($('#' + actionId).is(':checked')) {
                    actionIdreadonly = 'true';
                    break;
                  }
                }
              }
              if (actionIdreadonly == 'false') {
                if ($('#' + item.menuid).is(':checked')) {
                  (<HTMLInputElement>e6).checked = true;
                }
              }
              else {
                (<HTMLInputElement>e6).checked = false;
              }
            }
          }
        });
      }
    });
  }
  roleChange(menuMapped: any) {
    // this.SpinnerService.show();
    var array = menuMapped;
    if ((array != null) && (array != undefined)) {
      array.forEach(data => {
        if (data.action.length != 0) {
          this._menuList.forEach(item => {
            if (item.menuid === data.menuid) {
              let e2 = document.getElementById(data.menuid);
              (<HTMLInputElement>e2).checked = true;
              // check the action checkbox
              data.action.forEach(a => {
                const actionChkName = data.menuid + '_' + a;
                const e3 = document.getElementById(actionChkName);
                (<HTMLInputElement>e3).checked = true;
                this.onCheckboxChange(data.menuid, a, true);
              });
            }
          });
        } else { this.checkedAll = true; }
      });
    }
    //  this.SpinnerService.hide();
  }

}


