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 { Subskill } from './subskill';
import { Skill } from '../skill/skill';
import { SubskillService } from './subskill.service';

@Component({
  selector: 'app-subskill',
  templateUrl: './subskill.component.html',
  styleUrls: ['./subskill.component.css']
})
export class SubskillComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'skill';
  _menuId: any;
  actionRights: any;
  submitShow: boolean;
  readOnly: boolean; add: boolean; edit: boolean; delete: boolean;
  subskillForm: FormGroup;
  subskills: Subskill[] = [];
  subskillsactive: Subskill[] = [];
  skillsactive: Skill[] = [];
  subskill: Subskill;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  subskillModalRef: BsModalRef;
  operation: string;
  userid: number;
  subskillid: 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 = 'subskillname';
  reverse = false;

  constructor(private router: Router, private toastr: ToastrService, private dialogService: DialogService,
    private formBuilder: FormBuilder, private modalService: BsModalService, private subskillservice: SubskillService) { 
      if (this.router.getCurrentNavigation().extras.state !== undefined) {
        localStorage.setItem('Subskill_menuid', this.router.getCurrentNavigation().extras.state.menuid);
        localStorage.setItem('Subskill_userRights', this.router.getCurrentNavigation().extras.state.action);
        this.actionRights = [];
        this.actionRights = this.router.getCurrentNavigation().extras.state.action;
      } else {
        this.actionRights = [];
        this.actionRights = localStorage.getItem('Subskill_userRights');
      }
    }

  ngOnInit(): void {
    this.subskillForm = this.formBuilder.group({
      subskillid: [''],
      skillid: ['', [Validators.required]],
      subskillname: ['', [Validators.required]],
      active: ['']
    });
    this.searchText = '';
    this.getAll();
    this.getActiveSkill();
    this.readOnly = true;
    this.add = true;
    this.edit = true;
    this.delete = true;
    this.submitShow = true;
    this.getUserRights();
  }

  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.subskillsactive = [];
    this.showall = showallp;
    this.showallstatus = showallp;
    if (this.showall === true) {
      this.showall = false;
      this.subskills.forEach(data => {
        if (data.active === 1) {
          this.subskillsactive.push(data);
        }
      });
      this.subskills = [];
      this.subskills = this.subskillsactive;
    } else {
      this.showall = true;
      this.subskills = [];
      this.getAll();
    }
  }

  // assigning value from menu rights button
  getActionRightsList() {
    const btnToEnable = JSON.parse(this.actionRights);
    if (btnToEnable.length > 0) {
      btnToEnable.forEach(d => {
        if (d !== undefined) {
          if (d === 1) {
            this.readOnly = true;
          } else if (d === 2) {
            this.readOnly = true;
            this.add = true;
            this.submitShow = true;
          } else if (d === 3) {
            this.readOnly = true;
            this.edit = true;
            // this.submitShow = true;
          } else if (d === 4) {
            this.readOnly = true;
            this.delete = true;
          }
        }
      });
    }
  }

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

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

  getActiveSkill() {
    this.skillsactive = [];
    this.subskillservice.GetActiveSkill().subscribe(
      res => {
        if (res[0] != null && res[0] !== undefined) {
          this.skillsactive = JSON.parse(res[0]);
        }
      });
  }

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

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

  Post(subskill: Subskill) {

    this.submitted = true;

    if ((subskill.subskillname.trim() === undefined) || (subskill.subskillname.trim() === '')) {
      this.toastr.error('skill should not be empty');
      return;
    }

    let msg = null;

    this.userid = +localStorage.getItem('userid');
    subskill.subskillname = subskill.subskillname.trim();
   // subskill.skillid = this.subskillForm.value.skillid;
   subskill.skillid = +subskill.skillid;
    if (this.operation === 'add') {

      subskill.createdby = this.userid;
      msg = 'Record Added Successfully';
      this.subskillservice.Post(subskill).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.subskillModalRef.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') {
      this.submitShow = true;
      subskill.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.subskillservice.Put(subskill).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.subskillModalRef.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.subskillForm.controls['active'].setValue(1);
    } else {
      this.subskillForm.controls['active'].setValue(0);
    }
  }

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

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

  }

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

  opensubskillModal(template: TemplateRef<any>, type, subskill?: Subskill) {

    this.operation = type;

    if (type === 'update') {
      this.subskillForm.controls['subskillid'].setValue(subskill.subskillid);
      this.subskillForm.controls['skillid'].setValue(subskill.skillid);
      this.subskillForm.controls['subskillname'].setValue(subskill.subskillname);
      this.subskillForm.controls['active'].setValue(subskill.active);
      this.subskill = subskill;
    }
    if (type === 'add') {
      this.subskillForm.controls['subskillid'].setValue(0);
      this.subskillForm.controls['skillid'].setValue(0);
      this.subskillForm.controls['subskillname'].setValue('');
      this.subskillForm.controls['active'].setValue(1);
    }
    this.subskillModalRef = this.modalService.show(template, this.config);

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

  }

}
