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

@Component({
  selector: 'app-checklistdetails',
  templateUrl: './checklistdetails.component.html',
  styleUrls: ['./checklistdetails.component.css']
})

export class ChecklistdetailsComponent implements OnInit {

  sendMenuId: number;
  sendPageName = 'CheckList';
  // action rights
  _menuId: any;
  _actionRights: any;
  _checklistid: number;
  submitShow: boolean;
  readOnly: boolean;
  add: boolean;
  edit: boolean;
  delete: boolean;
  checklistForm: FormGroup;
  checklistdetails: Checklistdetails[] = [];
  checklistdetailsactive: Checklistdetails[] = [];
  checklistdetail: Checklistdetails;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  checklistModalRef: BsModalRef;
  operation: string;
  userid: number;
  checklistdetid: 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 = 'checklistdetail'; // set default
  reverse = false;
  actionRights: any;
  constructor (private router: Router, private toastr: ToastrService, private dialogService: DialogService,
    private formBuilder: FormBuilder, private modalService: BsModalService, private checklistservice: ChecklistdetailsService,
    private route: ActivatedRoute
    ) {
      this._checklistid = +this.route.snapshot.queryParamMap.get('checklistid');
       // get rights for the logged in user for the particular component
     if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('CheckListDetails_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('CheckListDetails_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('CheckListDetails_userRights');
    }
    }

  ngOnInit(): void {
    this.checklistForm = this.formBuilder.group({
      checklistdetailid: [''],
      checklistdetail: ['', [Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.getAll(this._checklistid);

    // for action rights
    this.readOnly = true;
    this.add = true;
    this.edit = true;
    this.delete = true;
    this.submitShow = true;
  }

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

  clearForm() {
    // for action rights
    if (this.add === true) {
      this.submitShow = true;
    } else {
      this.submitShow = false; }
    this.checklistModalRef.hide();
  }

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

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

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

  Post(checklistdetails: Checklistdetails) {

    this.submitted = true;

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

    let msg = null;

    this.userid = +localStorage.getItem('userid');
    checklistdetails.checklistdetail = checklistdetails.checklistdetail.trim();
    checklistdetails.checklistid = this._checklistid;
    if (this.operation === 'add') {
      checklistdetails.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.checklistservice.Post(checklistdetails).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.checklistModalRef.hide();
              this.getAll(this._checklistid);
              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') {
      this.submitShow = true;
      checklistdetails.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.checklistservice.Put(checklistdetails).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.checklistModalRef.hide();
              this.getAll(this._checklistid);
              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(checklistdetail, template: TemplateRef<any>) {
    if (checklistdetail.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.checklistdetail = checklistdetail;
          this.Delete();
        }
      });
  }

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

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

  openCheckListModal(template: TemplateRef<any>, type, checklistdetails?: Checklistdetails) {

    this.operation = type;

    if (type === 'update') {
      this.checklistForm.controls['checklistdetailid'].setValue(checklistdetails.checklistdetailid);
      // this.checklistForm.controls['checklistid'].setValue(checklistdetails.checklistid);
      this.checklistForm.controls['checklistdetail'].setValue(checklistdetails.checklistdetail);
      this.checklistForm.controls['active'].setValue(checklistdetails.active);
      this.checklistdetail = checklistdetails;
    }
    if (type === 'add') {
      this.checklistForm.controls['checklistdetailid'].setValue(0);
      // this.checklistForm.controls['checklistid'].setValue('');
      this.checklistForm.controls['checklistdetail'].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');
  }
  GotoChecklist() {
    this.router.navigate(['/masters/checklist']);
  }
}
