import { Component, OnInit, TemplateRef  } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { FileMode } from './filemode';
import { BsModalRef, ModalOptions, BsModalService } from 'ngx-bootstrap';
import { FileModeService } from './filemode.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-filemode',
  templateUrl: './filemode.component.html',
  styleUrls: ['./filemode.component.css']
})
export class FilemodeComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'Filemode';
  _menuId: any;
  actionRights: any;
  readOnly = false; add = false; edit = false; delete = false;
  filemodeForm: FormGroup;
  filemodes: FileMode[] = [];
  filemodesactive: FileMode[] = [];
  filemode: FileMode;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  filemodeModalRef: BsModalRef;
  operation: string;
  userid: number;
  filemodeid: 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 = 'filemode';
  reverse = false;

  constructor(
    private filemodeservice: FileModeService,
    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('FileMode_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('FileMode_userRights', this.router.getCurrentNavigation().extras.state.action);
        this.actionRights = [];
        this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
        this.actionRights = [];
        this.actionRights = localStorage.getItem('FileMode_userRights');
    }
  }

  ngOnInit(): void {
    this.filemodeForm = this.formBuilder.group({
      filemodeid: [''],
      filemode: ['', [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.filemodesactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.filemodes.forEach(data => {
        if (data.active === 1) {
          this.filemodesactive.push(data);
        }
      });
      this.filemodes = [];
      this.filemodes = this.filemodesactive;
    } else {
      this.showall = true;
      this.filemodes = [];
      this.getAll();
    }
  }

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

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

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

  }

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

  Post(filemode: FileMode) {

    this.submitted = true;
    // stop here if form is invalid
    // if (this.filemodeForm.invalid) {
    //  console.log(this.g);
    //  console.log(this.filemodeForm.errors);
    // }

    if ((filemode.filemode.trim() === undefined) || (filemode.filemode.trim() === '')) {
      this.toastr.error('File Mode should not be empty');
      return;
    }

    let msg = null;

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

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

          this.Delete();
        }
      });
  }

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

  }

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

  openFilemodeModal(template: TemplateRef<any>, type, filemode?: FileMode) {

    this.operation = type;

    if (type === 'update') {
      this.filemodeForm.controls['filemodeid'].setValue(filemode.filemodeid);
      this.filemodeForm.controls['filemode'].setValue(filemode.filemode);
      this.filemodeForm.controls['active'].setValue(filemode.active);
      this.filemode = filemode;
    }
    if (type === 'add') {
      this.filemodeForm.controls['filemodeid'].setValue(0);
      this.filemodeForm.controls['filemode'].setValue('');
      this.filemodeForm.controls['active'].setValue(1);
    }
    this.filemodeModalRef = this.modalService.show(template, this.config);

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

  }

}
