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

@Component({
  selector: 'app-lobmaster',
  templateUrl: './lobmaster.component.html',
  styleUrls: ['./lobmaster.component.css']
})
export class LobmasterComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'LobList';
  // action rights
  _menuId: any;
  actionRights: any;
  readOnly = false; add = true; edit = true; delete = true;
  loblistForm: FormGroup;
  loblists: lobmaster[] = [];
  loblistsactive: lobmaster[] = [];
  loblist: lobmaster;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  loblistModalRef: BsModalRef;
  operation: string;
  userid: number;
  loblistid: 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 = 'lob'; // set default
  reverse = false;

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

  }

  ngOnInit() {
    this.loblistForm = this.formBuilder.group({
      lobid: [''],
      lob: ['', [Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.getAll();
    //this.getUserRights();
  }

  getactiveinactive(showallp) {
    this.loblistsactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.loblists.forEach(data => {
        if (data.active === 1) {
          this.loblistsactive.push(data);
        }
      });
      this.loblists = [];
      this.loblists = this.loblistsactive;
    } else {
      this.showall = true;
      this.loblists = [];
      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.loblistModalRef.hide();
  }

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


  getAll() {
    this.loblists = [];
    this.loblistsactive = [];
    this.lobservice.Get_all().subscribe(res => {
      this.lobservice.Get_all
      if (res.body != null && res.body !== undefined) {
        this.loblists = res.body;
        if (this.showallstatus === true) {
          this.loblists.forEach(data => {
            if (data.active === 1) {
              this.loblistsactive.push(data);
            }
          });
          this.loblists = [];
          this.loblists = this.loblistsactive;
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });

  }

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

  Post(loblist: lobmaster) {

    this.submitted = true;

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

    let msg = null;

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

      loblist.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.lobservice.Add_Lob(loblist).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.loblistModalRef.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') {
      loblist.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.lobservice.Edit_Lob(loblist).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {

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

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

          this.Delete();

        }

      });

  }

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

  }

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

  openlobModal(template: TemplateRef<any>, type, loblist?: lobmaster) {

    this.operation = type;

    if (type === 'update') {
      this.loblistForm.controls['lobid'].setValue(loblist.lobid);
      this.loblistForm.controls['lob'].setValue(loblist.lob);
      this.loblistForm.controls['active'].setValue(loblist.active);
      this.loblist = loblist;
    }
    if (type === 'add') {
      this.loblistForm.controls['lobid'].setValue(0);
      this.loblistForm.controls['lob'].setValue('');
      this.loblistForm.controls['active'].setValue(1);
    }
    this.loblistModalRef = this.modalService.show(template, this.config);

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

  }
  callloblistdetail(lobid: number) {
    this.router.navigate(['/masters/lobdetails'], { queryParams: { lobid: lobid } });
  }

}
