import { Component, OnInit, TemplateRef } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { PrintSupplement } from './printsupplement';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { PrintSupplementService } from './printsupplement.service';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { DialogService } from 'ng2-bootstrap-modal';
import { CommondialogComponent } from '../../Shared/commondialog/commondialog.component';
import { SupplementService } from 'src/app/chapterconfiguration/supplement/supplement.service';
declare var $: any;

@Component({
  selector: 'app-printsupplement',
  templateUrl: './printsupplement.component.html',
  styleUrls: ['./printsupplement.component.css']
})
export class PrintSupplementComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'PrintSupplement';
  // action rights
  _menuId: any;
  actionRights: any;
  readOnly = false; add = false; edit = false; delete = false;
  printsupplementForm: FormGroup;
  printsupplements: PrintSupplement[] = [];
  printsupplementsactive: PrintSupplement[] = [];
  printsupplement: PrintSupplement;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  printsupplementModalRef: BsModalRef;
  operation: string;
  userid: number;
  printsupplementid: 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 = 'printsupplement';
  reverse = false;
  supplementTypes: any = [];
  constructor(
    private printsupplementservice: PrintSupplementService,
    private modalService: BsModalService,
    private formBuilder: FormBuilder,
    private router: Router,
    private toastr: ToastrService,
    private dialogService: DialogService,
    private supplementService: SupplementService,) {

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

  }

  ngOnInit() {
    this.printsupplementForm = this.formBuilder.group({
      printsupplementid: [''],
      supplementacronym: ['', [Validators.required]],
      supplementnumber: ['', [Validators.required]],
      year: ['', [Validators.required]],
      publicationid: ['', [Validators.required]],
      scheduledate: ['', [Validators.required]],
      supplementtypeid: [0, [Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.showallstatus = true;
    this.getAll();

    this.getUserRights();
    this.GetAllSupplementType();
  }
 // 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.printsupplementsactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.printsupplements.forEach(data => {
        if (data.active === 1) {
          this.printsupplementsactive.push(data);
        }
      });
      this.printsupplements = [];
      this.printsupplements = this.printsupplementsactive;
    } else {
      this.showall = true;
      this.printsupplements = [];
      this.getAll();
    }
  }


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

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

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

  }

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

  Post(printsupplement: PrintSupplement) {

    this.submitted = true;
    if ((printsupplement.publicationid.trim() === undefined) || (printsupplement.publicationid.trim() === '')) {
      this.toastr.error('Publication ID should not be empty');
      return;
    }

    let msg = null;

    this.userid = +localStorage.getItem('userid');
    printsupplement.publicationid = printsupplement.publicationid.trim();
    printsupplement.supplementacronym = printsupplement.supplementacronym.trim();
    printsupplement.supplementnumber = printsupplement.supplementnumber.trim();
    printsupplement.supplementtypeid = +printsupplement.supplementtypeid;
    printsupplement.year = printsupplement.year.trim();
    if (this.operation === 'add') {
      printsupplement.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.printsupplementservice.Post(printsupplement).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.printsupplementModalRef.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') {
      printsupplement.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.printsupplementservice.Put(printsupplement).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.printsupplementModalRef.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.printsupplementForm.controls['active'].setValue(1);
    } else {
      this.printsupplementForm.controls['active'].setValue(0);
    }
  }

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

          this.Delete();
        }
      });
  }

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

  }

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

  openPrintSupplementModal(template: TemplateRef<any>, type, printsupplement?: PrintSupplement) {

    this.operation = type;

    if (type === 'update') {
      this.printsupplementForm.controls['printsupplementid'].setValue(printsupplement.printsupplementid);
      this.printsupplementForm.controls['publicationid'].setValue(printsupplement.publicationid);
      this.printsupplementForm.controls['supplementacronym'].setValue(printsupplement.supplementacronym);
      this.printsupplementForm.controls['supplementnumber'].setValue(printsupplement.supplementnumber);
      this.printsupplementForm.controls['year'].setValue(printsupplement.year);
      this.printsupplementForm.controls['active'].setValue(printsupplement.active);
      this.printsupplementForm.controls['supplementtypeid'].setValue(+printsupplement.supplementtypeid);
      this.printsupplementForm.controls['scheduledate'].setValue(printsupplement.scheduledate);
      this.printsupplement = printsupplement;
    }
    if (type === 'add') {
      this.printsupplementForm.controls['printsupplementid'].setValue(0);
      this.printsupplementForm.controls['publicationid'].setValue('');
      this.printsupplementForm.controls['supplementacronym'].setValue('');
      this.printsupplementForm.controls['supplementnumber'].setValue('');
      this.printsupplementForm.controls['supplementtypeid'].setValue(0);
      this.printsupplementForm.controls['year'].setValue('');
      this.printsupplementForm.controls['active'].setValue(1);
    }
    this.printsupplementModalRef = this.modalService.show(template, this.config);

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

  }
  GetAllSupplementType() {
    this.supplementTypes = [];
    this.supplementService.GetAllSupplementType().subscribe(res => {
      if (res.body[0] != null && res.body[0] !== undefined) {
        console.log('GetAllSupplementType=', JSON.parse(res.body[0]));
        this.supplementTypes = JSON.parse(res.body[0]);
        this.supplementTypes = this.supplementTypes.filter(y => y.active === 1);
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

}
