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 { Jobmeta } from './jobmeta';
import { JobmetaService } from './jobmeta.service';

@Component({
  selector: 'app-jobmeta',
  templateUrl: './jobmeta.component.html',
  styleUrls: ['./jobmeta.component.css']
})
export class JobMetaComponent implements OnInit {
  sendMenuId: number;
  sendPageName = 'Jobmeta';
  // action rights
  _menuId: any;
  _actionRights: any;
  readOnly = false; add = false; edit = false; delete = false;
  jobmetaForm: FormGroup;
  jobmetas: Jobmeta[] = [];
  jobmetasactive: Jobmeta[] = [];
  jobmeta: Jobmeta;
  deleteResult: boolean;
  postresult: boolean;
  putDResult: boolean;
  jobmetaModalRef: BsModalRef;
  operation: string;
  userid: number;
  jobmetaid: number;
  submitted = false;
  active: number;
  unamePattern: string;
  confmsg: string;
  p = 1; searchText: string;
  itemsPerPage = 10;
  metadataselectinputoptionflag=false;	
  selectoptionlist=[]; 

  _projectlist : any[];
  config: ModalOptions = {
    backdrop: 'static',
    keyboard: false,
    animated: true,
    class: 'modal-dialog-centered',
    ignoreBackdropClick: true
  };
  showall = true;
  showallstatus = false;
  key = 'jobmeta'; // set default
  reverse = false;
  actionRights: any;
  constructor(private router: Router, private toastr: ToastrService, private dialogService: DialogService,
    private formBuilder: FormBuilder, private modalService: BsModalService, private jobmetaservice: JobmetaService) {
     // get rights for the logged in user for the particular component
     if (this.router.getCurrentNavigation().extras.state !== undefined) {
      localStorage.setItem('Jobmeta_menuid', this.router.getCurrentNavigation().extras.state.menuid);
      localStorage.setItem('Jobmeta_userRights', this.router.getCurrentNavigation().extras.state.action);
      this.actionRights = [];
      this.actionRights = this.router.getCurrentNavigation().extras.state.action;
    } else {
      this.actionRights = [];
      this.actionRights = localStorage.getItem('Jobmeta_userRights');
    }
  }

  ngOnInit() {
    this.jobmetaForm = this.formBuilder.group({
      jobmetaid: [''],
      jobmeta: ['', [Validators.required]],
      projectdefinitionid:[''],
      isexcelmeta:[''],
      active: [''], 
      isrequired:[''],
      inputtype:[''],
      selectoption:['']
    });
    this.searchText = '';
    this.getAll();

    // for action rights
    this.getUserRights();
  }

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

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


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

  }

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

  Post(jobmeta: Jobmeta) {
debugger;
    this.submitted = true;

    if ((jobmeta.jobmeta.trim() === undefined) || (jobmeta.jobmeta.trim() === '')) {
      this.toastr.error('AllocationType should not be empty');
      return;
    }
    if(+jobmeta.isexcelmeta===0){
      jobmeta.isexcelmeta = false;
    }
    if(+jobmeta.isrequired===0){
      jobmeta.isrequired = false;
    }
    if(+jobmeta.inputtype===0){
      this.toastr.error('Kindly choose input type.');
      return;
    }
    else{
      if(jobmeta.inputtype ==='dropdown' || jobmeta.inputtype==='checkbox'){
        if(this.selectoptionlist=== undefined || this.selectoptionlist=== null){
          this.toastr.error('Kindly enter option list for dropdown type input.');
          return;
        }
      }
    }

    let msg = null;

    this.userid = +localStorage.getItem('userid');
    jobmeta.jobmeta = jobmeta.jobmeta.trim();
    if(jobmeta.inputtype ==='dropdown' || jobmeta.inputtype==='checkbox'){ jobmeta.inputvalueoption = JSON.stringify(this.selectoptionlist.map(i => ({Fieldselectoption: i.Fieldselectoption})));}
    if (this.operation === 'add') {
      jobmeta.createdby = this.userid;
      msg = 'Record Added Successfully';
      jobmeta.projectdefinitionid = Number(jobmeta.projectdefinitionid);
      this.jobmetaservice.Post(jobmeta).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.jobmetaModalRef.hide();
              this.metadataselectinputoptionflag = false;
              this.selectoptionlist=[];
              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') {
           jobmeta.updatedby = this.userid;
      msg = 'Record updated successfully';
      this.jobmetaservice.Put(jobmeta).subscribe(res => {
        if (res.status === 200) {
          if (res !== undefined) {
            if (res.body !== 0) {
              this.jobmetaModalRef.hide();
              this.metadataselectinputoptionflag = false;
              this.selectoptionlist=[];
              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.jobmetaForm.controls['active'].setValue(1);
    } else {
      this.jobmetaForm.controls['active'].setValue(0);
    }
  }

  OpenConfirmTemplate(jobmeta) {
    if (jobmeta.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.jobmeta = jobmeta;

          this.Delete();

        }

      });

  }

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

  }

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

  getprojectdeflst(){
    this.userid = +localStorage.getItem('userid');
    this.jobmetaservice.Get_projectdeflst(this.userid).subscribe(res => {
      debugger;
      if (res != null && res !== undefined) {
        this._projectlist =res;
      }
    }, error => { this.toastr.error('Error while getting data'); });
  }

  openJobMetaModal(template: TemplateRef<any>, type, jobmeta?: Jobmeta) {
   debugger;
    this.operation = type;
    this.getprojectdeflst();
    if (type === 'update') {
      console.log(jobmeta.inputtype)
      this.jobmetaForm.controls['jobmetaid'].setValue(jobmeta.jobmetaid);
      this.jobmetaForm.controls['jobmeta'].setValue(jobmeta.jobmeta);
      this.jobmetaForm.controls['active'].setValue(jobmeta.active);
      this.jobmetaForm.controls['projectdefinitionid'].setValue(jobmeta.projectdefinitionid);
      this.jobmetaForm.controls['isexcelmeta'].setValue(jobmeta.isexcelmeta);
      this.jobmetaForm.controls['isrequired'].setValue(jobmeta.isrequired);
      this.jobmetaForm.controls['inputtype'].setValue(jobmeta.inputtype);
      if(jobmeta.inputtype==="dropdown" || jobmeta.inputtype === "checkbox"){
        if(jobmeta.inputvalueoption===null || jobmeta.inputvalueoption==='' || jobmeta.inputvalueoption=== undefined){
          this.metadataselectinputoptionflag = true;
          this.selectoptionlist=[];
        }
        else{
          let inputvalueoptionlist=[];
          inputvalueoptionlist.push(jobmeta.inputvalueoption);
          this.selectoptionlist=inputvalueoptionlist[0];
          this.metadataselectinputoptionflag = true;
        }
      }else if(jobmeta.inputtype==="text" || jobmeta.inputtype==="date" || jobmeta.inputtype === null){
        this.selectoptionlist=[];
        this.metadataselectinputoptionflag = false;
      }   
      this.jobmeta = jobmeta;
    }
    if (type === 'add') {
      this.jobmetaForm.controls['jobmetaid'].setValue(0);
      this.jobmetaForm.controls['jobmeta'].setValue('');
      this.jobmetaForm.controls['active'].setValue(1);
      this.jobmetaForm.controls['projectdefinitionid'].setValue(0);
      this.jobmetaForm.controls['isexcelmeta'].setValue(0);
      this.jobmetaForm.controls['isrequired'].setValue(0);
      this.jobmetaForm.controls['inputtype'].setValue('0');
      this.jobmetaForm.controls['selectoption'].setValue('');
      this.metadataselectinputoptionflag = false;
      this.selectoptionlist=[];

    }
    this.jobmetaModalRef = this.modalService.show(template, this.config);

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

  }

  onchangeinputtype(operation) {
    debugger;
    console.log(this.jobmetas);
    if(this.jobmetaForm.controls['inputtype'].value == "dropdown" || this.jobmetaForm.controls['inputtype'].value == "checkbox" ){
      this.metadataselectinputoptionflag = true;
       if(operation=="update"){
        this.jobmetas.forEach(val=>{
          if(val.jobmetaid===this.jobmetaForm.controls['jobmetaid'].value){
            if(val.inputvalueoption !=null && val.inputvalueoption !='' && val.inputvalueoption != undefined){
              let inputvalueoptionlist=[];
              inputvalueoptionlist.push(val.inputvalueoption);
              this.selectoptionlist=inputvalueoptionlist[0];
            }
            else{
              this.selectoptionlist=[];
            }
          }
        });
      } 
    }
    else{
      this.metadataselectinputoptionflag = false;
      this.jobmetaForm.controls['selectoption'].setValue(null);
      this.selectoptionlist=[];
    }
  }
  addselectoptionlist(){
    debugger;
    this.selectoptionlist.push({
      Fieldselectoption: this.jobmetaForm.controls['selectoption'].value
    });
    this.jobmetaForm.controls['selectoption'].setValue(null);
  }
  updateselectoptionlist(item){
    debugger;
    console.log(this.selectoptionlist);
    const index: number = this.selectoptionlist.indexOf(item);
      if (index !== -1) {
          this.selectoptionlist.splice(index, 1);
      } 
    console.log(this.selectoptionlist);
  }

}
