import { Component, OnInit, TemplateRef } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Miptopic3 } from './miptopic3';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { Miptopic3Service } from './miptopic3.service';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { DialogService } from 'ng2-bootstrap-modal';
import { CommondialogComponent } from '../../Shared/commondialog/commondialog.component';
declare var $: any;

@Component({
  selector: 'app-miptopic3',
  templateUrl: './miptopic3.component.html',
  styleUrls: ['./miptopic3.component.css']
})
export class Miptopic3Component implements OnInit {
  sendMenuId: number;
  sendPageName = 'Miptopic3';
  // action rights
  _menuId: any;
  actionRights: any;
  readOnly = false; add = false; edit = false; delete = false;
  miptopic3Form: FormGroup;
  miptopic3s: Miptopic3[] = [];
  miptopic3sactive: Miptopic3[] = [];
  miptopic3: Miptopic3;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  miptopic3ModalRef: BsModalRef;
  operation: string;
  userid: number;
  miptopic3id: 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 = 'miptopic3';
  reverse = false;
  constructor(
    private miptopic3service: Miptopic3Service,
    private modalService: BsModalService,
    private formBuilder: FormBuilder,
    private router: Router,
    private toastr: ToastrService,
    private dialogService: DialogService) {

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

  }

  ngOnInit() {
    this.miptopic3Form = this.formBuilder.group({
      miptopic3id: [''],
      miptopic3: ['', [Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.showallstatus = true;
    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.miptopic3sactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.miptopic3s.forEach(data => {
        if (data.active === 1) {
          this.miptopic3sactive.push(data);
        }
      });
      this.miptopic3s = [];
      this.miptopic3s = this.miptopic3sactive;
    } else {
      this.showall = true;
      this.miptopic3s = [];
      this.getAll();
    }
  }


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

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

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

  }

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

  Post(miptopic3: Miptopic3) {

    this.submitted = true;
    if ((miptopic3.miptopic3.trim() === undefined) || (miptopic3.miptopic3.trim() === '')) {
      this.toastr.error('MIP Topic3 should not be empty');
      return;
    }

    let msg = null;

    this.userid = +localStorage.getItem('userid');
    miptopic3.miptopic3 = miptopic3.miptopic3.trim();
    if (this.operation === 'add') {
      miptopic3.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.miptopic3service.Post(miptopic3).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.miptopic3ModalRef.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') {
      miptopic3.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.miptopic3service.Put(miptopic3).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.miptopic3ModalRef.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.miptopic3Form.controls['active'].setValue(1);
    } else {
      this.miptopic3Form.controls['active'].setValue(0);
    }
  }

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

          this.Delete();
        }
      });
  }

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

  }

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

  openMiptopic3Modal(template: TemplateRef<any>, type, miptopic3?: Miptopic3) {

    this.operation = type;

    if (type === 'update') {
      this.miptopic3Form.controls['miptopic3id'].setValue(miptopic3.miptopic3id);
      this.miptopic3Form.controls['miptopic3'].setValue(miptopic3.miptopic3);
      this.miptopic3Form.controls['active'].setValue(miptopic3.active);
      this.miptopic3 = miptopic3;
    }
    if (type === 'add') {
      this.miptopic3Form.controls['miptopic3id'].setValue(0);
      this.miptopic3Form.controls['miptopic3'].setValue('');
      this.miptopic3Form.controls['active'].setValue(1);
    }
    this.miptopic3ModalRef = this.modalService.show(template, this.config);

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

  }

}
