import { Component, OnInit, TemplateRef } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { Miptopic1 } from './miptopic1';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { Miptopic1Service } from './miptopic1.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-miptopic1',
  templateUrl: './miptopic1.component.html',
  styleUrls: ['./miptopic1.component.css']
})
export class Miptopic1Component implements OnInit {
  sendMenuId: number;
  sendPageName = 'Miptopic1';
  // action rights
  _menuId: any;
  actionRights: any;
  readOnly = false; add = false; edit = false; delete = false;
  miptopic1Form: FormGroup;
  miptopic1s: Miptopic1[] = [];
  miptopic1sactive: Miptopic1[] = [];
  miptopic1: Miptopic1;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  miptopic1ModalRef: BsModalRef;
  operation: string;
  userid: number;
  miptopic1id: 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 = 'miptopic1';
  reverse = false;
  constructor(
    private miptopic1service: Miptopic1Service,
    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('Miptopic1_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Miptopic1_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Miptopic1_userRights');
    }

  }

  ngOnInit() {
    this.miptopic1Form = this.formBuilder.group({
      miptopic1id: [''],
      miptopic1: ['', [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.miptopic1sactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.miptopic1s.forEach(data => {
        if (data.active === 1) {
          this.miptopic1sactive.push(data);
        }
      });
      this.miptopic1s = [];
      this.miptopic1s = this.miptopic1sactive;
    } else {
      this.showall = true;
      this.miptopic1s = [];
      this.getAll();
    }
  }


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

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

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

  }

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

  Post(miptopic1: Miptopic1) {

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

    let msg = null;

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

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

          this.Delete();
        }
      });
  }

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

  }

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

  openMiptopic1Modal(template: TemplateRef<any>, type, miptopic1?: Miptopic1) {

    this.operation = type;

    if (type === 'update') {
      this.miptopic1Form.controls['miptopic1id'].setValue(miptopic1.miptopic1id);
      this.miptopic1Form.controls['miptopic1'].setValue(miptopic1.miptopic1);
      this.miptopic1Form.controls['active'].setValue(miptopic1.active);
      this.miptopic1 = miptopic1;
    }
    if (type === 'add') {
      this.miptopic1Form.controls['miptopic1id'].setValue(0);
      this.miptopic1Form.controls['miptopic1'].setValue('');
      this.miptopic1Form.controls['active'].setValue(1);
    }
    this.miptopic1ModalRef = this.modalService.show(template, this.config);

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

  }

}
