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 { CheckList } from './checklist';
import { ChecklistService } from './checklist.service';

@Component({
  selector: 'app-checklist',
  templateUrl: './checklist.component.html',
  styleUrls: ['./checklist.component.css']
})
export class ChecklistComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'CheckList';
  // action rights
  _menuId: any;
  actionRights: any;
  readOnly = false; add = false; edit = false; delete = false;
  checklistForm: FormGroup;
  checklists: CheckList[] = [];
  checklistsactive: CheckList[] = [];
  checklist: CheckList;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  checklistModalRef: BsModalRef;
  operation: string;
  userid: number;
  checklistid: 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 = 'checklist'; // set default
  reverse = false;

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

  }

  ngOnInit() {
    this.checklistForm = this.formBuilder.group({
      checklistid: [''],
      checklist: ['', [Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.getAll();
    this.getUserRights();
  }

  getactiveinactive(showallp) {
    this.checklistsactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.checklists.forEach(data => {
        if (data.active === 1) {
          this.checklistsactive.push(data);
        }
      });
      this.checklists = [];
      this.checklists = this.checklistsactive;
    } else {
      this.showall = true;
      this.checklists = [];
      this.getAll();
    }
  }

  // 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;
          }
        }
      });
    }
  }

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

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


  getAll() {
    this.checklists = [];
    this.checklistsactive = [];
    this.checklistservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.checklists = JSON.parse(res[0]);
        if (this.showallstatus === true) {
          this.checklists.forEach(data => {
            if (data.active === 1) {
              this.checklistsactive.push(data);
            }
          });
          this.checklists = [];
          this.checklists = this.checklistsactive;
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });

  }

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

  Post(checklist: CheckList) {

    this.submitted = true;

    if ((checklist.checklist.trim() === undefined) || (checklist.checklist.trim() === '')) {
      this.toastr.error('CheckList should not be empty');
      return;
    }

    let msg = null;

    this.userid = +localStorage.getItem('userid');
    checklist.checklist = checklist.checklist.trim();
    if (this.operation === 'add') {

      checklist.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.checklistservice.Post(checklist).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.checklistModalRef.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') {
      checklist.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.checklistservice.Put(checklist).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {

            if (res.body !== 0) {
              this.checklistModalRef.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.checklistForm.controls['active'].setValue(1);
    } else {
      this.checklistForm.controls['active'].setValue(0);
    }
  }

  OpenConfirmTemplate(checklist) {
    if (checklist.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.checklist = checklist;

          this.Delete();

        }

      });

  }

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

  }

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

  openCheckListModal(template: TemplateRef<any>, type, checklist?: CheckList) {

    this.operation = type;

    if (type === 'update') {
      this.checklistForm.controls['checklistid'].setValue(checklist.checklistid);
      this.checklistForm.controls['checklist'].setValue(checklist.checklist);
      this.checklistForm.controls['active'].setValue(checklist.active);
      this.checklist = checklist;
    }
    if (type === 'add') {
      this.checklistForm.controls['checklistid'].setValue(0);
      this.checklistForm.controls['checklist'].setValue('');
      this.checklistForm.controls['active'].setValue(1);
    }
    this.checklistModalRef = this.modalService.show(template, this.config);

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

  }
  callchecklistdetail(checklistid: number) {
    this.router.navigate(['/masters/checklistdetails'], { queryParams: { checklistid: checklistid } });
  }
}
