import { Component, OnInit, OnDestroy } from '@angular/core';
import { AuthService } from '../../services/auth.service';
import { Subject } from 'rxjs/Subject';
import { EmployeeHttpService } from 'app/services/employee/employee-http.service';
import { LocalStorageService } from 'angular-2-local-storage';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';

import {error, log} from "util";
import {forEach} from "@angular/router/src/utils/collection";
import {Router,ActivatedRoute} from "@angular/router";
import { environment } from '../../../environments/environment.dev';

const img_path_prefix = environment.imageUrl+'/assets/img/employee/shared/';
const img_path_suffix = '.png';

@Component({
  selector: 'app-pgm-assign-coach',
  templateUrl: './pgm-assign-coach.component.html',
  styleUrls: ['./pgm-assign-coach.component.scss']
})

export class PgmAssignCoachComponent implements OnInit {

  private $destroyed = new Subject();
  private currentUser: any;
  courses: any = [];
  recommendedCourses: any = [];
  courseCategories = [];
  selectedCoursesDetails: any = [];
  selectedCourses: any = [];
  selectedEmployeeDetails: any = [];
  selectedEmployee: any = [];
  coaches : any = [];
  selectCoach : any = [];
  selectedCoursesEmployeeDetails: any = [];
  courseEmployeLists: any = [];
  empLists = [];
  UserID:any
  fullName:any;
  name:any
  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any
  };

  CourseID : any

  statusOf = 'beforeRecommended';
  // statusOf = 'afterRecommended';
  imageUrl = environment.imageUrl;
  constructor(
    private employeeHttpService: EmployeeHttpService,
    private localStorageService: LocalStorageService,
    private AuthService:AuthService,
    private router:Router,
    private route:ActivatedRoute,
    private toastr: ToastsManager,

  ) {

    this.route.params.subscribe( params =>
      this.UserID = params['userId']
    )
    this.route.params.subscribe( params =>
      this.CourseID = params['courseId']
    )

    if(!this.UserID || this.UserID == null || !this.CourseID || this.CourseID == null) {
      this.router.navigate(['pgm/landing']);
    }
    else {

      var empData
      empData = this.localStorageService.get('userInfo');
      this.empData = empData
      console.log(this.empData,"userInfo Detailssssss")
      if(window.location.origin == 'http://localhost:8080'){
        this.name = 'SABASH'
        this.fullName = 'SABASH LS'
        this.getCoachesforCandidate(1,[1,2]);
        //this.getCoachCandidates(13,"Chennai", 1);
      }
      else {
        if (this.empData['firstName']) {
          this.name = this.empData['firstName'];
          this.fullName = this.empData['fullName'];
        }
        else {
          this.name = ''
          this.fullName = ''
        }
        this.getCoachesforCandidate(this.empData.location, this.empData.skills[0]);
        //this.getCourseAndEmployeeDetails(this.UserID,this.CourseID)
      }

      this.getCourseAndEmployeeDetails(this.UserID,this.CourseID)
    }

  }


  getCourseAndEmployeeDetails(userId,courseId){

    Promise.all([

      this.AuthService.getRecommendedCourses(userId,''),
      this.AuthService.getTestDetails({userInfoMstrId:userId})]
    )
      .then(arr => {

        console.log(arr)

        let courseRecommend = arr[0];
        let employeeDetails = arr[1];
        let listAllEmp = [];
        let recommendEmployee = [];

        let AllCourses = []
        let eventDetails = []
        let allRecommendedCoures = []


        Object.keys(courseRecommend).forEach(function (key) {

            if (key.toString() == userId.toString()) {

              courseRecommend[key].forEach(course => {


                if(course.pgCourseDetails.courseDetailsId == courseId){
                  var coursePG =  course.pgCourseDetails;

                  coursePG.candidate = employeeDetails.infoDetails
                  coursePG['selected'] = false

                  listAllEmp.push(course)
                }

              })

             // employeeDetails.infoDetails.userInfoMstr.pgCourseDtls = courseRecommend[key]
            }
        })


        console.log(listAllEmp,'courseeeeeeeee')

        this.courseEmployeLists = listAllEmp
        this.selectedCoursesEmployeeDetails = listAllEmp

        this.courseEmployeLists =  this.courseEmployeLists.map(course => course.pgCourseDetails);
        this.selectedCoursesEmployeeDetails =  this.selectedCoursesEmployeeDetails.map(course => course.pgCourseDetails);
        console.log(this.courseEmployeLists,'this.courseEmployeListsthis.courseEmployeLists')
        console.log(this.selectedCoursesEmployeeDetails,'this.selectedCoursesEmployeeDetails')



        document.getElementById('openModalButton').click();

      }).catch(error => {

        console.log(error,'error')
    })

  }

  getCoachesforCandidate(Location,SkillId){
    this.coaches = []
    this.AuthService.getAllCoachesforCandidate({location:Location, skillId:SkillId}).then(responseData =>{
      console.log(responseData,'getAllCoaches')

      for(var value of responseData.userInfoDtls){
        console.log(value.userInfoMstr.fullName)
        if(value.userInfoMstr.fullName != null){
          this.coaches.push(value);
        }
      }

      console.log(this.coaches,'getAllCoachessss');
    }).catch(err=>{
      console.log(err)
    });
  }

  ngOnInit() {

  }

  ngOnDestroy() {
    this.$destroyed.next();
    this.$destroyed.complete();
  }

  onSelectionChange (emp,status) {
    console.log(emp, 'selected Employeeee',status);

    if (status){
      this.selectedEmployee = Object.assign({}, this.selectedEmployee, emp);
      console.log(this.selectedEmployee, 'selected Employeeee');

      this.selectedEmployeeDetails.push(emp)
    }

  }



  closeModal()
  {
    console.log('closeModal');
    document.getElementById('closeAssignCoachModal').click()
  }

  assignBtnClick(){

    if(this.courseEmployeLists.length != 0) {
      document.getElementById('openModalButton').click();
    }
    else {
      this.toastr.error('Select one or more courses before assigning a Coach')
    }
  }
  Intials(cString) {
    if(cString) {
      return cString.replace(/\W*(\w)\w*/g, '$1').toUpperCase()
    }
  }

  onSelectCoach(coach){
    console.log(coach);
    this.selectCoach = coach;
    console.log(this.selectCoach,'selctedCoach')
  }

  scheduleAssignCoach(){
    console.log('ok');
    console.log(this.selectCoach,'selectCoach');
    console.log(this.courseEmployeLists,'courseEmployeLists')
    var assignCoach = {
      courseDetails:[]
    }
    this.courseEmployeLists.forEach(data =>{

      assignCoach.courseDetails.push({
        "coachId": this.selectCoach,
        "courseId": data.courseDetailsId,
        "userInfoMstrId": data.candidate.userInfoMstr.userInfoMstrId
      })
    })

    console.log(assignCoach,'AssignCoach PayLoad');


    this.AuthService.assignCoachForEmployee(assignCoach).then(resp => {
      console.log(resp,'AssignCoachForEmployee Responce')

      document.getElementById('closeAssignCoachModal').click()
      this.toastr.success(resp['status']);
      this.router.navigate(['pgm/landing']);

    }).catch(err => {

      console.log(err,'error')


      this.toastr.error('Something went wrong...!')

    })

  }

}

