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

@Component({
  selector: 'app-skill',
  templateUrl: './skill.component.html',
  styleUrls: ['./skill.component.css']
})
export class SkillComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'skill';
  _menuId: any;
  actionRights: any;
  submitShow: boolean;
  readOnly: boolean; add: boolean; edit: boolean; delete: boolean;
  skillForm: FormGroup;
  skills: Skill[] = [];
  skillsactive: Skill[] = [];
  skill: Skill;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  skillModalRef: BsModalRef;
  operation: string;
  userid: number;
  skillid: 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 = 'skillname';
  reverse = false;

  constructor(private router: Router, private toastr: ToastrService, private dialogService: DialogService,
    private formBuilder: FormBuilder, private modalService: BsModalService, private skillservice: SkillService) {

      if (this.router.getCurrentNavigation().extras.state !== undefined) {
        localStorage.setItem('Skill_menuid', this.router.getCurrentNavigation().extras.state.menuid);
        localStorage.setItem('Skill_userRights', this.router.getCurrentNavigation().extras.state.action);
        this.actionRights = [];
        this.actionRights = this.router.getCurrentNavigation().extras.state.action;
      } else {
        this.actionRights = [];
        this.actionRights = localStorage.getItem('Skill_userRights');
      }
    }

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

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

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


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

  }

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

  Post(skill: Skill) {

    this.submitted = true;

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

    let msg = null;

    this.userid = +localStorage.getItem('userid');
    skill.skillname = skill.skillname.trim();
    if (this.operation === 'add') {

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

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

          this.Delete();

        }

      });

  }

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

  }

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

  openskillModal(template: TemplateRef<any>, type, skill?: Skill) {

    this.operation = type;

    if (type === 'update') {
      this.skillForm.controls['skillid'].setValue(skill.skillid);
      this.skillForm.controls['skillname'].setValue(skill.skillname);
      this.skillForm.controls['active'].setValue(skill.active);
      this.skill = skill;
    }
    if (type === 'add') {
      this.skillForm.controls['skillid'].setValue(0);
      this.skillForm.controls['skillname'].setValue('');
      this.skillForm.controls['active'].setValue(1);
    }
    this.skillModalRef = this.modalService.show(template, this.config);

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

  }

}
