import { Component, OnInit, TemplateRef } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Department } from './department';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { DepartmentService } from './department.service';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { DialogService } from 'ng2-bootstrap-modal';
import { CommondialogComponent } from '../../Shared/commondialog/commondialog.component';
declare var $: any;

@Component({
  selector: 'app-department',
  templateUrl: './department.component.html',
  styleUrls: ['./department.component.css']
})
export class DepartmentComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'Department';
  // action rights
  _menuId: any;
  actionRights: any;
  readOnly = false; add = false; edit = false; delete = false;
  departmentForm: FormGroup;
  departments: Department[] = [];
  departmentsactive: Department[] = [];
  department: Department;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  departmentModalRef: BsModalRef;
  operation: string;
  userid: number;
  departmentid: 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 = 'department';
  reverse = false;
  constructor(
    private departmentservice: DepartmentService,
    private modalService: BsModalService,
    private formBuilder: FormBuilder,
    private router: Router,
    private toastr: ToastrService,
    private dialogService: DialogService) {

    // get rights for the logged in user for the particular component
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('Department_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Department_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Department_userRights');
    }

  }

  ngOnInit() {
    this.departmentForm = this.formBuilder.group({
      departmentid: [''],
      department: ['', [Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.showallstatus = true;
    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.departmentsactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.departments.forEach(data => {
        if (data.active === 1) {
          this.departmentsactive.push(data);
        }
      });
      this.departments = [];
      this.departments = this.departmentsactive;
    } else {
      this.showall = true;
      this.departments = [];
      this.getAll();
    }
  }


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

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

  getAll() {
    this.departments = [];
    this.departmentsactive = [];
    this.departmentservice.Get().subscribe(res => {
      this.departments = JSON.parse(res[0]);
      if (this.showallstatus === true) {
        this.departments.forEach(data => {
          if (data.active === 1) {
            this.departmentsactive.push(data);
          }
        });
        this.departments = [];
        this.departments = this.departmentsactive;
      }
    }, error => { this.toastr.error('Error while getting data'); });

  }

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

  Post(department: Department) {

    this.submitted = true;
    if ((department.department.trim() === undefined) || (department.department.trim() === '')) {
      this.toastr.error('Department should not be empty');
      return;
    }

    let msg = null;

    this.userid = +localStorage.getItem('userid');
    department.department = department.department.trim();
    if (this.operation === 'add') {
      department.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.departmentservice.Post(department).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.departmentModalRef.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') {
      department.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.departmentservice.Put(department).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.departmentModalRef.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.departmentForm.controls['active'].setValue(1);
    } else {
      this.departmentForm.controls['active'].setValue(0);
    }
  }

  OpenConfirmTemplate(department, template: TemplateRef<any>) {
    if (department.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.department = department;

          this.Delete();
        }
      });
  }

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

  }

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

  openDepartmentModal(template: TemplateRef<any>, type, department?: Department) {

    this.operation = type;

    if (type === 'update') {
      this.departmentForm.controls['departmentid'].setValue(department.departmentid);
      this.departmentForm.controls['department'].setValue(department.department);
      this.departmentForm.controls['active'].setValue(department.active);
      this.department = department;
    }
    if (type === 'add') {
      this.departmentForm.controls['departmentid'].setValue(0);
      this.departmentForm.controls['department'].setValue('');
      this.departmentForm.controls['active'].setValue(1);
    }
    this.departmentModalRef = this.modalService.show(template, this.config);

    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');

  }

}
