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 { Unit } from './unit';
import { UnitService } from './unit.service';

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

  sendMenuId: number;
  sendPageName = 'Unit';
  _menuId: any;
  actionRights: any;
  submitShow: boolean;
  readOnly = false; add = false; edit = false; delete = false;
  unitForm: FormGroup;
  units: Unit[] = [];
  unitsactive: Unit[] = [];
  unit: Unit;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  unitModalRef: BsModalRef;
  operation: string;
  userid: number;
  unitid: 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 = 'unitname';
  reverse = false;

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

  ngOnInit() {
    this.unitForm = this.formBuilder.group({
      unitid: [''],
      unitname: ['', [Validators.required]],
      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.unitsactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.units.forEach(data => {
        if (data.active === 1) {
          this.unitsactive.push(data);
        }
      });
      this.units = [];
      this.units = this.unitsactive;
    } else {
      this.showall = true;
      this.units = [];
      this.getAll();
    }
  }

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

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


  getAll() {
    this.units = [];

    this.unitservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.units = JSON.parse(res[0]);
        if (this.showallstatus === true) {
          this.units = this.units.filter(y => y.active === 1);

        }
      }
    }, error => { this.toastr.error('Error while getting data'); });

  }

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

  Post(unit: Unit) {
    this.submitted = true;

    if ((unit.unitname.trim() === undefined) || (unit.unitname.trim() === '')) {
      this.toastr.error('Unit name should not be empty');
      return;
    }

    let msg = null;

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

      unit.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.unitservice.Post(unit).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.unitModalRef.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') {
      this.submitShow = true;
      unit.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.unitservice.Put(unit).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.unitModalRef.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.unitForm.controls['active'].setValue(1);
    } else {
      this.unitForm.controls['active'].setValue(0);
    }
  }

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

          this.Delete();

        }

      });

  }

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

  }

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

  openUnitModal(template: TemplateRef<any>, type, unit?: Unit) {

    this.operation = type;

    if (type === 'update') {
      this.unitForm.controls['unitid'].setValue(unit.unitid);
      this.unitForm.controls['unitname'].setValue(unit.unitname);
      this.unitForm.controls['active'].setValue(unit.active);

      this.unit = unit;
    }
    if (type === 'add') {
      this.unitForm.reset();
      this.unitForm.controls['unitid'].setValue(0);
      this.unitForm.controls['active'].setValue(1);
    }
    this.unitModalRef = this.modalService.show(template, this.config);

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

  }

}
