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

@Component({
  selector: 'app-plugin',
  templateUrl: './plugin.component.html',
  styleUrls: ['./plugin.component.css']
})
export class PluginComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'Plugin';
  // action rights
  _menuId: any;
  _actionRights: any;
  readOnly = false; add = false; edit = false; delete = false;
  pluginForm: FormGroup;
  plugin: Plugins[] = [];
  pluginsactive: Plugins[] = [];
  Plugin: Plugins;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  pluginModalRef: BsModalRef;
  operation: string;
  userid: number;
  pluginid: 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 = 'Plugin'; // set default
  reverse = false;
  actionRights: any;
  constructor(private router: Router, private toastr: ToastrService, private dialogService: DialogService,
    private formBuilder: FormBuilder, private modalService: BsModalService, private pluginservice: PluginService) {
    // get rights for the logged in user for the particular component
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('Plugin_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Plugin_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Plugin_userRights');
    }
  }

  ngOnInit() {
    debugger;
    this.pluginForm = this.formBuilder.group({
      pluginid: [''],
      plugin: ['', [Validators.required]],
      displayname: [''],
      description: [''],
      active: ['']
    });
    this.searchText = '';
    this.getAll();
    // for action rights
    this.getUserRights();
  }

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

  // 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;
          }
        }
      });
    }
  }

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

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


  getAll() {
    this.plugin = [];
    this.pluginsactive = [];
    this.pluginservice.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this.plugin = JSON.parse(res[0]);
        if (this.showallstatus === true) {
          this.plugin.forEach(data => {
            if (data.active === 1) {
              this.pluginsactive.push(data);
            }
          });
          this.plugin = [];
          this.plugin = this.pluginsactive;
        }
      }
    }, error => { this.toastr.error('Error while getting data'); });

  }

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

  Post(plugin: Plugins) {
    this.submitted = true;
    if ((plugin.plugin.trim() === undefined) || (plugin.plugin.trim() === '')) {
      this.toastr.error('Plugin should not be empty');
      return;
    }
    if ((plugin.displayname.trim() === undefined) || (plugin.displayname.trim() === '')) {
      this.toastr.error('Display Name should not be empty');
      return;
    }
    let msg = null;
    this.userid = +localStorage.getItem('userid');
    plugin.plugin = plugin.plugin.trim();
    plugin.displayname = plugin.displayname.trim();
    plugin.description = plugin.description.trim();
    if (this.operation === 'add') {
      plugin.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.pluginservice.Post(plugin).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.pluginModalRef.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') {
      plugin.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.pluginservice.Put(plugin).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.pluginModalRef.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.pluginForm.controls['active'].setValue(1);
    } else {
      this.pluginForm.controls['active'].setValue(0);
    }
  }

  OpenConfirmTemplate(plugin) {
    if (plugin.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.Plugin = plugin;
          this.Delete();
        }
      });
  }

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

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

  openPluginModal(template: TemplateRef<any>, type, plugin?: Plugins) {
    this.operation = type;
    if (type === 'update') {
      this.pluginForm.controls['pluginid'].setValue(plugin.pluginid);
      this.pluginForm.controls['plugin'].setValue(plugin.plugin);
      this.pluginForm.controls['displayname'].setValue(plugin.displayname);
      this.pluginForm.controls['description'].setValue(plugin.description);
      this.pluginForm.controls['active'].setValue(plugin.active);
      this.Plugin = plugin;
    }
    if (type === 'add') {
      this.pluginForm.controls['pluginid'].setValue(0);
      this.pluginForm.controls['plugin'].setValue('');
      this.pluginForm.controls['displayname'].setValue('');
      this.pluginForm.controls['description'].setValue('');
      this.pluginForm.controls['active'].setValue(1);
    }
    this.pluginModalRef = this.modalService.show(template, this.config);
    const aa = document.getElementsByClassName('modal-content');
    aa[0].classList.remove('modal-content');
  }
}

