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

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

  sendMenuId: number;
  sendPageName = 'lobList';
  // action rights
  _menuId: any;
  _actionRights: any;
  _lobid: number;
  submitShow: boolean;
  readOnly: boolean;
  add: boolean;
  edit: boolean;
  delete: boolean;
  loblistForm: FormGroup;
  loblistdetails: Lobdetails_model[] = [];
  loblistdetailsactive: Lobdetails_model[] = [];
  loblistdetail: Lobdetails_model;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  loblistModalRef: BsModalRef;
  operation: string;
  userid: number;
  loblistdetid: 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 = 'queestion'; // set default
  reverse = false;
  actionRights: any;
  constructor (private router: Router, private toastr: ToastrService, private dialogService: DialogService,
    private formBuilder: FormBuilder, private modalService: BsModalService, private lobdetailsservice: LobdetailsService,
    private route: ActivatedRoute
    ) {
      this._lobid= +this.route.snapshot.queryParamMap.get('lobid');
       // get rights for the logged in user for the particular component
     if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('lobListDetails_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('lobListDetails_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('lobListDetails_userRights');
    }
    }

  ngOnInit(): void {
    this.loblistForm = this.formBuilder.group({
      questionid: [''],
      lobid: [''],
      question: ['', [Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.getAll(this._lobid);

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

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

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

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

  getAll(lobid: number) {
    this.loblistdetails = [];
    this.loblistdetailsactive = [];
    let input = [];
    let item = {
      lobid: lobid
    };
    input.push(item);
    this.lobdetailsservice.Get_Lobdetailslst(input[0]).subscribe(res => {
      if (res.body != null && res.body !== undefined) {
        this.loblistdetails = res.body;
        if (this.showallstatus === true) {
          this.loblistdetails.forEach(data => {
            if (data.active === 1) {
              this.loblistdetailsactive.push(data);
            }
          });
          this.loblistdetails = [];
          this.loblistdetails = this.loblistdetailsactive;
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });

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

  Post(loblistdetails: Lobdetails_model) {

    this.submitted = true;

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

    let msg = null;

    this.userid = +localStorage.getItem('userid');
    loblistdetails.question = loblistdetails.question.trim();
    loblistdetails.lobid = this._lobid;
    if (this.operation === 'add') {
      loblistdetails.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.lobdetailsservice.Add_Lobdetails(loblistdetails).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.loblistModalRef.hide();
              this.getAll(this._lobid);
              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;
      loblistdetails.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.lobdetailsservice.Edit_Lobdetails(loblistdetails).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.loblistModalRef.hide();
              this.getAll(this._lobid);
              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.lobed) {
      this.loblistForm.controls['active'].setValue(1);
    } else {
      this.loblistForm.controls['active'].setValue(0);
    }
  }

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

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

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

  openlobModal(template: TemplateRef<any>, type, loblistdetails?: Lobdetails_model) {

    this.operation = type;

    if (type === 'update') {
      this.loblistForm.controls['questionid'].setValue(loblistdetails.questionid);
      this.loblistForm.controls['lobid'].setValue(loblistdetails.lobid);
      this.loblistForm.controls['question'].setValue(loblistdetails.question);
      this.loblistForm.controls['active'].setValue(loblistdetails.active);
      this.loblistdetail = loblistdetails;
    }
    if (type === 'add') {
      this.loblistForm.controls['questionid'].setValue(0);
      this.loblistForm.controls['lobid'].setValue(this._lobid);
      this.loblistForm.controls['question'].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');
  }
  Gotoloblist() {
    this.router.navigate(['/masters/lobmaster']);
  }
}
