import { Component, OnInit, TemplateRef } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Miptopic2 } from './miptopic2';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { Miptopic2Service } from './miptopic2.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-miptopic2',
  templateUrl: './miptopic2.component.html',
  styleUrls: ['./miptopic2.component.css']
})
export class Miptopic2Component implements OnInit {
  sendMenuId: number;
  sendPageName = 'Miptopic2';
  // action rights
  _menuId: any;
  actionRights: any;
  readOnly = false; add = false; edit = false; delete = false;
  miptopic2Form: FormGroup;
  miptopic2s: Miptopic2[] = [];
  miptopic2sactive: Miptopic2[] = [];
  miptopic2: Miptopic2;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  miptopic2ModalRef: BsModalRef;
  operation: string;
  userid: number;
  miptopic2id: 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 = 'miptopic2';
  reverse = false;
  constructor(
    private miptopic2service: Miptopic2Service,
    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('Miptopic2_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Miptopic2_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Miptopic2_userRights');
    }

  }

  ngOnInit() {
    this.miptopic2Form = this.formBuilder.group({
      miptopic2id: [''],
      miptopic2: ['', [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.miptopic2sactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.miptopic2s.forEach(data => {
        if (data.active === 1) {
          this.miptopic2sactive.push(data);
        }
      });
      this.miptopic2s = [];
      this.miptopic2s = this.miptopic2sactive;
    } else {
      this.showall = true;
      this.miptopic2s = [];
      this.getAll();
    }
  }


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

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

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

  }

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

  Post(miptopic2: Miptopic2) {

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

    let msg = null;

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

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

          this.Delete();
        }
      });
  }

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

  }

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

  openMiptopic2Modal(template: TemplateRef<any>, type, miptopic2?: Miptopic2) {

    this.operation = type;

    if (type === 'update') {
      this.miptopic2Form.controls['miptopic2id'].setValue(miptopic2.miptopic2id);
      this.miptopic2Form.controls['miptopic2'].setValue(miptopic2.miptopic2);
      this.miptopic2Form.controls['active'].setValue(miptopic2.active);
      this.miptopic2 = miptopic2;
    }
    if (type === 'add') {
      this.miptopic2Form.controls['miptopic2id'].setValue(0);
      this.miptopic2Form.controls['miptopic2'].setValue('');
      this.miptopic2Form.controls['active'].setValue(1);
    }
    this.miptopic2ModalRef = this.modalService.show(template, this.config);

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

  }

}
