import { Component, OnInit, TemplateRef } from '@angular/core';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { Router } from '@angular/router';
import { CommondialogComponent } from 'src/app/Shared/commondialog/commondialog.component';
import { ToastrService } from 'ngx-toastr';
import { DialogService } from 'ng2-bootstrap-modal';
import { Menu } from './menu';
import { MenuService } from './menu.service';

@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit {

  sendMenuId: number;
  sendPageName = 'Menu';
  _menuId: any;
  actionRights: any;
  readOnly = false; add = false; edit = false; delete = false;
  menuForm: FormGroup;
  menus: Menu[] = [];
  menusactive: Menu[] = [];
  menu: Menu;
  parentmenus: Menu[] = [];
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  menuModalRef: BsModalRef;
  operation: string;
  userid: number;
  menuid: number;
  submitted = false;
  active: number;
  unamePattern: string;
  confmsg: string;
  p = 1; searchText: string;
  itemsPerPage = 10;
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered',
    ignoreBackdropClick: true
  };
  showall = true;
  showallstatus = false;
  key = 'menu';
  reverse = false;

  constructor(private router: Router, private toastr: ToastrService, private dialogService: DialogService,
    private formBuilder: FormBuilder, private modalService: BsModalService, private menuservice: MenuService) {
     // get rights for the logged in user for the particular component
     if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('Menu_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Menu_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Menu_userRights');
    }

  }

  ngOnInit() {
    this.menuForm = this.formBuilder.group({
      menuid: [''],
      menu: ['', [Validators.required]],
      tooltip: [''],
      menuiconpath: [''],
      sequenceno: [],
      action: [''],
      issubmenu: [1],
      parentmenuid: [0],
      active: ['']
    });
    this.searchText = '';
    this.getAll();
this.getUserRights();
  }
 // function to get user rights
 getUserRights() {
  const btnToEnable = JSON.parse(this.actionRights);
  if (btnToEnable.length > 0) {
    this.readOnly = true;
    btnToEnable.forEach(d => {
      if (d !== undefined) {
        if (d === 2) {
          this.add = true;
        } else if (d === 3) {
          this.edit = true;
        } else if (d === 4) {
          this.delete = true;
        }
      }
    });
  }
}

  getactiveinactive(showallp) {
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.menus = this.menus.filter(m => m.active === 1);
    } else {
      this.showall = true;
      this.menus = [];
      this.getAll();
    }
  }


  clearForm() {
   this.menuModalRef.hide();
  }

  sort(key) {
    this.key = key;
    this.reverse = !this.reverse;
  }


  getAll() {
    this.menus = [];
    this.menusactive = [];
    this.menuservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.menus = JSON.parse(res[0]);
        this.parentmenus = this.menus.filter(y => y.parentmenuid === 0);
        if (this.showallstatus === true) {
          this.menus = this.menus.filter(y => y.active === 1);
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  get g() { return this.menuForm.controls; }

  Post(menu: Menu) {
    this.submitted = true;
    if ((menu.menu.trim() === undefined) || (menu.menu.trim() === '')) {
      this.toastr.error('Menu should not be empty');
      return;
    }
    let msg = null;
    this.userid = +localStorage.getItem('userid');
    menu.menu = menu.menu.trim();
    menu.parentmenuid = +menu.parentmenuid;
    (menu.parentmenuid !== 0) ? menu.issubmenu = 1 : menu.issubmenu = 0;
    if (this.operation === 'add') {
      menu.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.menuservice.Post(menu).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.menuModalRef.hide();
              this.getAll();
              this.toastr.success('Data added successfully');
              this.clearForm();
            } else { this.toastr.warning('Record already exists.'); }
          }
        }
      },
        error => {
          this.toastr.error('Error while doing the operation');
          this.postresult = false;
        });
    } else if (this.operation = 'update') {
      menu.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.menuservice.Put(menu).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.menuModalRef.hide();
              this.getAll();
              this.toastr.success('Data updated successfully');
              this.clearForm();
            } else { this.toastr.warning('Record already exists.'); }
          }
        }
      },
        error => {
          this.toastr.error('Error while doing the operation');
          this.postresult = false;
        });
    }

    this.submitted = false;
  }

  ChangeActive(e) {
    if (e.currentTarget.checked) {
      this.menuForm.controls['active'].setValue(1);
    } else {
      this.menuForm.controls['active'].setValue(0);
    }
  }

  OpenConfirmTemplate(menu) {
    if (menu.active === 0) {
      this.confmsg = 'activate';
    } else {
      this.confmsg = 'deactivate';
    }
    this.dialogService.addDialog(CommondialogComponent,
      {
        title: 'Please Confirm',
        message: 'Are you sure you want to ' + this.confmsg + ' this record ?',
        hclass: 'modelsuccess',
        oktext: 'Yes',
        canceltext: 'No',
        okshow: true,
        cancelshow: true
      }).subscribe((isConfirmed) => {
        if (isConfirmed) {
          this.menu = menu;
          this.Delete();
        }
      });
  }

  Delete() {
    let msg;
    if (this.menu.active === 0) {
      this.menu.active = 1;
      msg = 'Record activated successfully';
    } else {
      this.menu.active = 0;
      msg = 'Record deactivated successfully';
    }
    this.userid = +localStorage.getItem('userid');
    this.menu.updatedby = this.userid;
    this.menuservice.Delete(this.menu).subscribe(res => {
      this.toastr.success(msg);
      this.getAll();
    },
      error => { this.deleteResult = false; });
  }

  hidePopup() {
    this.menuModalRef.hide();
  }

  openMenuModal(template: TemplateRef<any>, type, menu?: Menu) {
    this.operation = type;
    if (type === 'update') {
      this.menuForm.controls['menuid'].setValue(menu.menuid);
      this.menuForm.controls['menu'].setValue(menu.menu);
      this.menuForm.controls['tooltip'].setValue(menu.tooltip);
      this.menuForm.controls['menuiconpath'].setValue(menu.menuiconpath);
      this.menuForm.controls['sequenceno'].setValue(menu.sequenceno);
      this.menuForm.controls['action'].setValue(menu.action);
      this.menuForm.controls['issubmenu'].setValue(menu.issubmenu);
      this.menuForm.controls['parentmenuid'].setValue(menu.parentmenuid);
      this.menuForm.controls['active'].setValue(menu.active);
      this.menu = menu;
    }
    if (type === 'add') {
      this.menuForm.reset();
      this.menuForm.controls['menuid'].setValue(0);
      this.menuForm.controls['active'].setValue(1);
      this.menuForm.controls['sequenceno'].setValue(1);
      this.menuForm.controls['parentmenuid'].setValue(0);
    }
    this.menuModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }
}
