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 'src/app/Shared/commondialog/commondialog.component';
import { ToastrService } from 'ngx-toastr';
import { DialogService } from 'ng2-bootstrap-modal';
import { Toolset } from './toolset';
import { ToolsetService } from './toolset.service';
import { PluginService } from '../plugin/plugin.service';
@Component({
  selector: 'app-toolset',
  templateUrl: './toolset.component.html',
  styleUrls: ['./toolset.component.css']
})
export class ToolsetComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'Toolset';
  // action rights
  _menuId: any;
  _actionRights: any;
  readOnly = false; add = false; edit = false; delete = false;
  toolsetForm: FormGroup;
  toolsets: Toolset[] = [];
  toolsetsactive: Toolset[] = [];
  toolset: Toolset;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  toolsetModalRef: BsModalRef;
  operation: string;
  userid: number;
  toolsetid: 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 = 'toolset'; // set default
  reverse = false;
  actionRights: any;
  _plugins: any = [];
  _dropdownSettings: any;
  _selectedItems: any = [];
  constructor(private router: Router, private toastr: ToastrService, private dialogService: DialogService,
    private formBuilder: FormBuilder, private modalService: BsModalService,
    private toolsetservice: ToolsetService, private pluginService: PluginService) {
    // get rights for the logged in user for the particular component
    if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('Toolset_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Toolset_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Toolset_userRights');
    }
  }

  ngOnInit() {
    this.toolsetForm = this.formBuilder.group({
      toolsetid: [''],
      toolset: ['', [Validators.required]],
      plugins: [''],
      active: ['']

    });
    this.searchText = '';
    this.getAll();
    // for action rights
    this.getUserRights();
    this.getTools();
  }

  getactiveinactive(showallp) {
    this.toolsetsactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.toolsets.forEach(data => {
        if (data.active === 1) {
          this.toolsetsactive.push(data);
        }
      });
      this.toolsets = [];
      this.toolsets = this.toolsetsactive;
    } else {
      this.showall = true;
      this.toolsets = [];
      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.toolsetModalRef.hide();
  }

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

  getTools() {
    this.pluginService.Get().subscribe(res => {
      if (res[0] != null && res[0] !== undefined) {
        this._plugins = JSON.parse(res[0]);
        this._plugins = this._plugins.filter(p => p.active === 1);
        console.log('this._plugins=', this._plugins);
        // this._plugins = res;
        this._dropdownSettings = {
          singleSelection: false,
          idField: 'pluginid',
          textField: 'displayname',
          selectAllText: 'Select All',
          unSelectAllText: 'UnSelect All',
          itemsShowLimit: 10,
          allowSearchFilter: true
        };
      }
    }, error => { this.toastr.error('Error while getting plugin data'); });

  }

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

  }

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

  Post(toolset: Toolset) {
    this.submitted = true;
    if ((toolset.toolset.trim() === undefined) || (toolset.toolset.trim() === '')) {
      this.toastr.error('Toolset should not be empty');
      return;
    } else if (toolset.plugins.length === 0) {
      this.toastr.error('Plugins should not be empty');
      return;
    }
    let msg = null;
    this.userid = +localStorage.getItem('userid');
    toolset.toolset = toolset.toolset.trim();
    toolset.plugins = JSON.stringify(toolset.plugins);
    if (this.operation === 'add') {
      toolset.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.toolsetservice.Post(toolset).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.toolsetModalRef.hide();
              this._selectedItems = [];
              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') {
      toolset.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.toolsetservice.Put(toolset).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.toolsetModalRef.hide();
              this._selectedItems = [];
              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.toolsetForm.controls['active'].setValue(1);
    } else {
      this.toolsetForm.controls['active'].setValue(0);
    }
  }

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

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

  }

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

  openToolsetModal(template: TemplateRef<any>, type, toolset?: Toolset) {
    this.operation = type;
    if (type === 'update') {
      this.toolsetForm.controls['toolsetid'].setValue(toolset.toolsetid);
      this.toolsetForm.controls['toolset'].setValue(toolset.toolset);
      this.toolset = toolset;
      // const pluginss = JSON.parse(JSON.stringify(toolset.plugins));
      // if (pluginss.length > 0) {
      //   this._plugins.forEach((plugins, i) => {
      //     pluginss.forEach((pplugins, ind) => {
      //       if (plugins.toolsid === pplugins.toolsid) {
      //         this._selectedItems.push(plugins);
      //       }
      //     });
      //   });
      //   this.toolsetForm.controls['active'].setValue(toolset.active);
      //   this.toolset = toolset;
      // }
      this._selectedItems = JSON.parse(JSON.stringify(toolset.plugins));
      console.log('this._selectedItems=', this._selectedItems);
      this.toolsetForm.controls['active'].setValue(toolset.active);
    }
    if (type === 'add') {
      this.toolsetForm.controls['toolsetid'].setValue(0);
      this.toolsetForm.controls['toolset'].setValue('');
      // this.toolsetForm.controls['address'].setValue('');
      // this.toolsetForm.controls['email'].setValue('');
      // this.toolsetForm.controls['contactnumber'].setValue('');
      // this.toolsetForm.controls['iconnectcode'].setValue(0);
      this.toolsetForm.controls['active'].setValue(1);
      this._selectedItems = [];
    }
    this.toolsetModalRef = this.modalService.show(template, this.config);

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

  }
}
