import { Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
import { AuthService } from '../../../../../services/auth.service';
import { FormBuilder, FormGroup, Validators, AbstractControl } from '@angular/forms';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import _ from "lodash";
import InnovationUrls from '../../../../../services/innovation/innovation-urls';
import { environment } from '../../../../../../environments/environment.dev';
import { LocalStorageService } from 'angular-2-local-storage';

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

  newjrFormdet: any
  skilltrackResponse: Skilltrackdetails [];
  Skills: string;
  sandboxes : any;
  selectedSkillValues: any;
  skillArrJr : any = [];
  primChallange: any;
  UpdateBtn: boolean = false;
  editDisabled: boolean;
  whiteBoardScn: any;
  codingCUC: any;
  accountDets: any;
  fullName: string;
  reqData: any;
  errMsg: any;
  userInfoMstrId: number;
  emailId: any;
  coachList: any;

  @Input() jrEditDet: any;
  @Output() closeJrForm = new EventEmitter<string>();
  @Output() closeEdJrForm = new EventEmitter<any>();

  constructor(private AuthService: AuthService,
    private toastr: ToastsManager, protected localStorageService: LocalStorageService) { 
      this.reqData = this.localStorageService.get('userInfo');
      console.log(this.reqData);
      this.fullName = this.reqData['fullName'];
      this.emailId = this.reqData['emailId'];
      this.userInfoMstrId = this.reqData['userInfoMstrId'];
      console.log(this.fullName, this.emailId, this.userInfoMstrId);

      this.getAllSkills();
      this.getAllAccounts();
    }

  ngOnInit() {
    this.newjrFormdet = {};
    if(this.jrEditDet){
      console.log(JSON.stringify(this.jrEditDet));
      this.newjrFormdet.skills = this.jrEditDet.skills;
      this.getCoachesBySkill(this.newjrFormdet.skills);
      this.viewDetailAssment(this.newjrFormdet.skills);
      this.getCodingChallenge(this.newjrFormdet.skills);
      this.getSandboxList(this.newjrFormdet.skills);
      this.newjrFormdet.coaches = this.jrEditDet.coaches;
      // this.newjrFormdet.skills = this.jrEditDet.skillId;
      // if(this.jrEditDet.skillId){
      //   this.newjrFormdet.skills.push(this.jrEditDet.skillId);
      //   console.log("edit skill data -- ",this.newjrFormdet.skills);
      //   this.onSkillMaster(null, this.newjrFormdet.skills);
      // }
      this.newjrFormdet.jobTitle = this.jrEditDet.requirementName;
      this.newjrFormdet.description =this.jrEditDet.requirementDesc;
      this.newjrFormdet.assesment = this.jrEditDet.primaryChallengeId;
      this.newjrFormdet.codingChallengeUseCaseId = this.jrEditDet.codingChallengeId;
      this.newjrFormdet.sandboxId = this.jrEditDet.sandboxId;
      this.newjrFormdet.accountId = this.jrEditDet.accountId;
      this.UpdateBtn = true;
      this.editDisabled = true;
      console.log(this.newjrFormdet);
    }

    // this.coachList = [{"userInfomstrId":43,"fullName":"ishtiaq"},{"userInfomstrId":1,"fullName": 'Shuchita'},{"userInfomstrId":15,"fullName":'sandhya'}, {"userInfomstrId":104,"fullName":'murali'},{"userInfomstrId":105,"fullName": 'srinivas'}];
  }

  getSandboxList(id){
    this.AuthService.getAllAwsDirectoryBundleJR(id).then(resp => {
        // console.log(resp, 'getAllAwsDirectoryBundleJR');
        // this.tableData.rows = this.sandboxes.map(function (item, index, array) {
        //   return [item.pgSkillTrackMstr.skillTrackName, item.bundleId, item.directoryId];
        // });
        if(resp.successMessage && resp.successMessage == "No record!"){
          this.sandboxes = [];
        }
        else{
          this.sandboxes = resp.pgAwsDirectoryBundleList;
        }
      }).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)
    })
  }

  // getWhiteBoardIsecases(id){
  //   this.AuthService.getAllWhiteBoardUc(id).then(resp => {
  //     console.log(resp, "WHiteboard scen..");
  //     this.whiteBoardScn = resp.useCaseList;
  //   })
  // }

  getCodingChallenge(id){
    this.AuthService.getAllCodingChallangeUc(id).then(resp => {
      // console.log(resp, "getAllCodingChallangeUc scen..");
      this.codingCUC = resp.useCaseList;
    })
  }

  getAllAccounts(){
    this.AuthService.getAllCaccounts().then(resp => {
      // console.log(resp, "getAllCodingChallangeUc scen..");
      this.accountDets = resp.accountsList;
    })
  }

  getCoachesBySkill(id){
    this.AuthService.getCoachesBySelectedSkills(id).then(resp => {
      console.log(resp, "getAllCodingChallangeUc scen..");
      this.coachList = resp;
    })
  }

  cancelForm(){
    this.newjrFormdet = {};
    this.closeJrForm.emit('true');
    console.log("cancel clicked");
  }
  cancelEdForm(newjrFormdet){
    console.log(newjrFormdet);
    this.closeEdJrForm.emit(newjrFormdet);
    this.newjrFormdet = {};
  }

  onSkillMaster(e, data){
    console.log(e);
    console.log("data -- "+JSON.stringify(data));
    this.selectedSkillValues = data;
    // this.skillArrJr = []; commented for multiselect
    console.log(this.selectedSkillValues);
    if(this.selectedSkillValues.length > 0){
    this.viewDetailAssment(data);
    // this.getWhiteBoardIsecases(data);
    this.getCodingChallenge(data);
    this.getSandboxList(data);
    this.getCoachesBySkill(data);
    }
  }

  updateCheckedOptions(id, e){
    if(e.target.checked === true ){
    this.skillArrJr.push(id);
    }
    else{
      this.skillArrJr.splice(this.skillArrJr.indexOf(id), 1)
    }
    this.newjrFormdet.skillTrackDtlsId = this.skillArrJr;
    console.log(this.newjrFormdet.skillTrackDtlsId );
  }

  viewDetailAssment(id) {
    this.AuthService.getCapabilityAssessmentsBySkill(id).then(resp => {
      if (resp.status == 'error') {
        this.toastr.error(resp.message);
      } else {
        // this.toastr.success(resp.successMessage);
        this.primChallange = resp.pgAssessmentDtls;
        // console.log('Detailed assmnt info', JSON.stringify(this.detailedAssesment));
      }
    })
  }

  createNewJR(){
    this.newjrFormdet.createdBy = this.fullName;
    this.newjrFormdet.updatedBy = this.fullName;
    this.newjrFormdet.levelOfExperience = null;
    this.newjrFormdet.location = null;
    console.log('REQUEST PAYLOAD -- ',JSON.stringify(this.newjrFormdet));
    
    this.errMsg = '';
    if(!this.newjrFormdet.skills || this.newjrFormdet.skills.length < 0){
      this.errMsg = 'Please select any one skill';
    }
    else if(!this.newjrFormdet.jobTitle){
      this.errMsg = 'Job Requirement Name cannot be empty';
    }
    else if(!this.newjrFormdet.description){
      this.errMsg = 'Job Requirement Description cannot be empty';
    }
    // else if(!this.newjrFormdet.codingChallengeUseCaseId || !this.newjrFormdet.assesment || !this.newjrFormdet.accountId || !this.newjrFormdet.sandboxId){
    //   this.errMsg = 'Please select any option in all of the provided dropdowns ';
    // }
    else if(this.newjrFormdet.assesment && !this.newjrFormdet.codingChallengeUseCaseId){
      this.errMsg = 'Please select any Coding Challenge from provided dropdown ';
    }
    else if(this.newjrFormdet.codingChallengeUseCaseId && !this.newjrFormdet.sandboxId){
      this.errMsg = 'Please select a Sandbox from provided dropdown ';
    }
    else{
      this.errMsg = '';
      this.AuthService.getaddJobRequirement(this.newjrFormdet).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, 'responseELSeeeeeeeeee')
          this.toastr.success('Job Requirement Created successfully');
          this.cancelForm();
        }
      }).catch(err => {
        console.log(err, "Error");
        this.toastr.error(err.error);
      })
    }
  }

  editExistingJR(){
    this.newjrFormdet.id = this.jrEditDet.requirementId;
    this.newjrFormdet.updatedBy = this.fullName;
    this.newjrFormdet.levelOfExperience = null;
    this.newjrFormdet.location = null;
    
    this.errMsg = '';
    if(!this.newjrFormdet.skills || this.newjrFormdet.skills.length < 0){
      this.errMsg = 'Please select any one skill';
    }
    else if(!this.newjrFormdet.jobTitle){
      this.errMsg = 'Job Requirement Name cannot be empty';
    }
    else if(!this.newjrFormdet.description){
      this.errMsg = 'Job Requirement Description cannot be empty';
    }
    // else if(!this.newjrFormdet.codingChallengeUseCaseId || !this.newjrFormdet.assesment || !this.newjrFormdet.accountId || !this.newjrFormdet.sandboxId){
    //   this.errMsg = 'Please select any option in all of the provided dropdowns ';
    // }
    else if(this.newjrFormdet.assesment && !this.newjrFormdet.codingChallengeUseCaseId){
      this.errMsg = 'Please select any Coding Challenge from provided dropdown ';
    }
    else if(this.newjrFormdet.codingChallengeUseCaseId && !this.newjrFormdet.sandboxId){
      this.errMsg = 'Please select a Sandbox from provided dropdown ';
    }
    else{
      console.log('in edit form req param -- ',JSON.stringify(this.newjrFormdet));
      this.errMsg = '';
      this.AuthService.geteditJobRequirement(this.newjrFormdet).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, 'responseELSeeeeeeeeee')
          this.toastr.success('Job Requirement Updated successfully');
          this.cancelForm();
        }
      }).catch(err => {
        console.log(err, "Error");
        this.toastr.error(err.error);
      })
    }
    
  }
}

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