import { Component, OnInit,Input, Output, EventEmitter } from '@angular/core';
import { NavBarService } from '../../../../admin.service';
import { AuthService } from '../../../../../services/auth.service';
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { BrowserModule } from '@angular/platform-browser';
import { MatCheckboxModule, MatInputModule } from '@angular/material';
import _ from "lodash";

@Component({
  selector: 'app-ca-form',
  templateUrl: './ca-form.component.html',
  styleUrls: ['./ca-form.component.scss']
})
export class CaFormComponent implements OnInit {

  skillSet: string;
  newcaFormdet: any;
  Skills: string;
  skilltrackResponse: Skilltrackdetails [];
  UpdateBtn: boolean;
  editDisabled: boolean;
  selectedSkillValues: any;
  errMsg = '';
  skillArrCa : any = [];
  mettlAsmnt: any;

  @Output() closeAssForm = new EventEmitter<string>();
  @Input() caEditDet: any;
  @Output() closeEdAssForm = new EventEmitter<any>();

  constructor(private navBarService: NavBarService,
    private AuthService: AuthService,
    private toastr: ToastsManager) { 
      this.getAllSkills();
      this.getAllMettlAssessment();
    }

  ngOnInit() {
    this.newcaFormdet = {};
    if(this.caEditDet){
      console.log(JSON.stringify(this.caEditDet));
      this.newcaFormdet.assessmentId = this.caEditDet.assessmentId;
      this.newcaFormdet.skillTrackMstrId = this.caEditDet.pgSkillTrackMstr.skillTrackMstrId;
      this.selectedSkillValues = this.newcaFormdet.skillTrackMstrId;
      this.newcaFormdet.skillTrackName = this.caEditDet.pgSkillTrackMstr.skillTrackName;
      this.newcaFormdet.assessmentDesc =this.caEditDet.assessmentDesc;
      this.newcaFormdet.passMarks = this.caEditDet.minPassMarks;
      this.newcaFormdet.assessmentName = this.caEditDet.assessmentName;
      if(this.caEditDet.testTakersCount == null){
        this.caEditDet.testTakersCount = '00';
      }
      this.newcaFormdet.testTakersCount = this.caEditDet.testTakersCount;
      this.UpdateBtn = true;
      this.editDisabled = true;
      if(this.caEditDet.pgAssessmentSkillMapping && this.caEditDet.pgAssessmentSkillMapping.length != 0){
        this.newcaFormdet.skillTrackName = this.caEditDet.pgAssessmentSkillMapping[0].pgSkillTrackDtls.pgSkillTrackMstr.skillTrackName;
        this.newcaFormdet.skillTrackMstrId = this.caEditDet.pgAssessmentSkillMapping[0].pgSkillTrackDtls.pgSkillTrackMstr.skillTrackMstrId;
        this.onSkillMaster(null, this.newcaFormdet.skillTrackMstrId);
        this.skillArrCa = this.caEditDet['pgAssessmentSkillMapping'].map((skillMap)=>skillMap['pgSkillTrackDtls']['skillTrackDtlsId'])
        }
        console.log(this.newcaFormdet);
    }
  }

  // getAllSkills(){
  //   this.AuthService.getAllSkillTrackMstr().then(resp =>{
  //     console.log(resp,'getAllSkillTrackMstr')
  //     this.skillSet = resp.pgSkillTrackMstr
  //   }).catch(err =>{
  //     console.log(err)
  //   })
  // }

  cancelForm(){
    this.newcaFormdet = {};
    this.closeAssForm.emit('true');
    console.log("cancel clicked");
  }
  cancelEdForm(newcaFormdet){
    console.log(newcaFormdet);
    this.closeEdAssForm.emit(newcaFormdet);
    this.newcaFormdet = {};
  }
  getAllMettlAssessment(){
    this.AuthService.getAllMettlAssessmentDtls().then(resp =>{
      this.mettlAsmnt = resp.assessments;
      console.log('Mettl Assessments', this.mettlAsmnt);
      // var customSkill = []
      // var skills = _.uniqBy(resp.pgSkillTrackDtlsList,'pgSkillTrackMstr.skillTrackName')
      // var masterSkills = _.uniqBy(_.flattenDeep(skills.map(i => i.pgSkillTrackMstr)))
      // masterSkills.forEach(usrSkills => {
      //   var dtlsSkill = resp.pgSkillTrackDtlsList.filter(item => item.pgSkillTrackMstr.skillTrackName == usrSkills.skillTrackName)
      //   var skillTrackDtlsName = _.uniqBy(_.flattenDeep(dtlsSkill.filter(i => {return {id : i.skillTrackDtlsId, name : i.skillTrackDtlsName}})))
      //   customSkill.push({skillMaster:usrSkills,skillTrackDtls :dtlsSkill,skillTrackDtlsName:skillTrackDtlsName});
      // });
      // console.log(customSkill);
      // this.skilltrackResponse = customSkill;
    }).catch(err =>{

      console.log(err)
    })
  }

  getAllSkills(){

    this.AuthService.getAllSkill().then(resp =>{
      console.log(resp,'getAllSkill')
      this.Skills = resp.pgSkillTrackDtlsList
      var customSkill = []
      var skills = _.uniqBy(resp.pgSkillTrackDtlsList,'pgSkillTrackMstr.skillTrackName')
      var masterSkills = _.uniqBy(_.flattenDeep(skills.map(i => i.pgSkillTrackMstr)))
      masterSkills.forEach(usrSkills => {
        var dtlsSkill = resp.pgSkillTrackDtlsList.filter(item => item.pgSkillTrackMstr.skillTrackName == usrSkills.skillTrackName)
        var skillTrackDtlsName = _.uniqBy(_.flattenDeep(dtlsSkill.filter(i => {return {id : i.skillTrackDtlsId, name : i.skillTrackDtlsName}})))
        customSkill.push({skillMaster:usrSkills,skillTrackDtls :dtlsSkill,skillTrackDtlsName:skillTrackDtlsName});
      });
      console.log(customSkill);
      this.skilltrackResponse = customSkill;
    }).catch(err =>{

      console.log(err)
    })
  }

  onSkillMaster(e, data){
    console.log(e);
    console.log("data -- "+JSON.stringify(data));
    this.selectedSkillValues = data;
    console.log(this.selectedSkillValues);
  }

  updateCheckedOptions(id, status){
    console.log("checkbox selected --- ", status.target.value, id, status);
    if(status.target.checked === true ){
    this.skillArrCa.push(id);
    }
    else{
      this.skillArrCa.splice(this.skillArrCa.indexOf(id), 1)
    }
    this.newcaFormdet.skillTrackDtlsId = this.skillArrCa;
    console.log(this.newcaFormdet.skillTrackDtlsId );
  }

  onSubmit(newcaFormdet) {
    console.log('you submitted value: ' +JSON.stringify(newcaFormdet));

    this.errMsg = ''
    if (newcaFormdet.skillTrackMstrId == undefined || newcaFormdet.skillTrackMstrId == null){
      this.errMsg = "Please Select skill set";
    }
    else if (newcaFormdet.assessmentId == '' || newcaFormdet.assessmentId == 'undefined' || newcaFormdet.assessmentId == null ){
      this.errMsg = "Please enter valid assessmentId";
    }
    else if (newcaFormdet.assessmentDesc == '' || newcaFormdet.assessmentDesc == 'undefined' || newcaFormdet.assessmentDesc == null ){
      this.errMsg = "Please enter valid assessmentDesc";
    }
    else if (newcaFormdet.passMarks == '' || newcaFormdet.passMarks == null || newcaFormdet.passMarks == 'undefined'){
      this.errMsg = "Please enter valid passmark";
    }
    // else if (newcaFormdet.description == '' || newcaFormdet.description == 'undefined' || newcaFormdet.description == null ){
    // this.errMsg = "Please enter description";
    // }
    else {
      this.AuthService.getaddAssessmentDetails(newcaFormdet).then(resp => {
        console.log(resp, 'response')
        if (resp.status == 'error') {
          this.errMsg = resp.message;
          this.toastr.error(resp.status, resp.message);
        }
        else {
          console.log(resp.error, 'responseELSeeeeeeeeee')
          this.toastr.success('Assesment Created successfully');
          this.newcaFormdet = {};
          this.closeAssForm.emit('true');
        }
      }).catch(err => {
        console.log(err, "Error");
        this.toastr.error(err.error);
      })
    }
  }

  onEditSubmit(newcaFormdet){
    if(!this.newcaFormdet.skillTrackDtlsId){
      this.newcaFormdet.skillTrackDtlsId = this.skillArrCa;
    }
    console.log('you submitted value: ' +JSON.stringify(newcaFormdet));
    this.errMsg = ''
    if (newcaFormdet.skillTrackMstrId == undefined || newcaFormdet.skillTrackMstrId == null){
      this.errMsg = "Please Select skill set";
    }
    else if (newcaFormdet.assessmentId == '' || newcaFormdet.assessmentId == 'undefined' || newcaFormdet.assessmentId == null ){
      this.errMsg = "Please enter valid assessmentId";
    }else if (newcaFormdet.assessmentDesc == '' || newcaFormdet.assessmentDesc == 'undefined' || newcaFormdet.assessmentDesc == null ){
      this.errMsg = "Please enter valid assessmentDesc";
    }
    else {

      //delete value['id']

      this.AuthService.getUpdateAssessmentDetails(newcaFormdet).then(resp => {

        console.log(resp, 'response')
        if (resp.status == 'error') {
          this.errMsg = resp.message
        }
        else {
          console.log(resp.error, 'responseELSeeeeeeeeee')
          this.toastr.success('Assesment Updated successfully');
          this.closeEdAssForm.emit(newcaFormdet);
          this.newcaFormdet = {};
        }
      }).catch(err => {
        console.log(err, "Error")
      })
    }
  }
}

interface Skilltrackdetails {
  pgSkillTrackDtlsList: {
  skillTrackDtlsId: number,
  pgSkillTrackMstr: {
      skillTrackMstrId: number,
      skillTrackName: string
  }
  skillTrackDtlsName: string
  }
}