import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../../services/auth.service';
import { LocalStorageService } from 'angular-2-local-storage';
import { Router } from '@angular/router';
import { NavigationService } from '../../../services/navigation/navigation.service';
import { WorkspaceService } from '../../../services/workspace.service';
import { NavBarService } from '../../coach.service';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { EmployeeCourseIdService } from 'app/coach/shared/service/employee-course-id.service';
import { CoachCandidateEvaluationService } from 'app/coach/shared/service/coach-candidate-evaluation.service';
import { coachEmployeeUpdateStatus } from 'app/models/coach-employee/udpateStatus';
import { log } from 'util';
import _ from 'lodash';
import { environment } from '../../../../environments/environment.dev';

@Component({
  selector: 'app-coachemployeedashboard',
  templateUrl: './coachemployeedashboard.component.html',
  styleUrls: ['./coachemployeedashboard.component.css']
})
export class CoachemployeedashboardComponent implements OnInit {

  userIcon = '';
  calledclass = '';
  Id= 95;
  public registeredCandidates;
  public listCandidates;
  Location = 'Chennai';
  SkillId = 1;
  filterActive = 'all';
  CFLANDING= false;
  loader = true;
  name: string;
  fullName: string;
  courseFilter: any = { userDetails: { infoDtls: { fullName: '' }}};
  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any
  };
  isAssessment: any;
  Skills: any;
  recommendedCol = false;
  primarySkillCandidateCount = 0;
  techUseCaseCandidateCount = 0;
  bussUseCaseCandidateCount = 0;
  primarySkillEvalCandidates = [];
  techUseCaseEvalCandidate = [];
  bussUseCaseEvalCandidate = [];
  filterprimarySkillEvalCandidates = [];
  filtertechUseCaseEvalCandidate = [];
  filterbussUseCaseEvalCandidate = [];
  recommendCourseEmployee = []
  updateemployeeStatus: coachEmployeeUpdateStatus;

  primaryFilter= [
    {
      'id': 'all',
      'name': 'All'
    },
    {
      'id': 'inProgress',
      'name': 'In Progress'
    },
    {
      'id': 'notScheduled',
      'name': 'Schedule'
    },
    {
      'id': 'evaluation',
      'name': 'Evaluation'
    },
    {
      'id': 'completed',
      'name': 'Completed'
    }
  ];
  filter = [
    {
      'id': 'all',
      'name': 'All'
    },
    {
      'id': 'inProgress',
      'name': 'In Progress'
    },
    {
      'id': 'evaluation',
      'name': 'Evaluation'
    },
    {
      'id': 'completed',
      'name': 'Completed'
    }
  ];
  imageUrl: string = environment.imageUrl;
  img_path = environment.imageUrl+'/assets/img/Taflow/';

  constructor(protected localStorageService: LocalStorageService,
              private AuthService: AuthService,
              private router: Router,
              private navigate: NavigationService,
              private navBarService: NavBarService,
              private toastr: ToastsManager,
              private WorkspaceService: WorkspaceService,
              private EmployeeCourseIdService: EmployeeCourseIdService,
              private CoachCandidateEvaluationService: CoachCandidateEvaluationService) {

    this.navBarService.setCurrentPage(0);
    this.CoachCandidateEvaluationService.setProperActiveTab(1);
    let empData;
    empData = this.localStorageService.get('userInfo');
    this.empData = empData;
    console.log(this.empData, 'userInfo Detailssssss');
    if (window.location.origin === 'http://localhost:8080') {
      this.name = 'UDAYANI';
      this.fullName = 'UDAYANI CHAVA';
      this.getCoachEmployees(4);
    } else {
      if (this.empData['firstName']) {
        this.name = this.empData['firstName'];
        this.fullName = this.empData['fullName'];
      } else {
        this.name = '';
        this.fullName = '';
      }
      this.getCoachEmployees(this.empData.userInfoMstrId);
    }
  }

  ngOnInit() {
  }

  recommend() {
    this.recommendedCol = true;
  }

  selectedRecommend(assess){

    this.isAssessment = assess;
    this.getAllSkills()
    document.getElementById('openSkillModal').click();

  }

  getAllSkills(){


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

  skillSelect (skillVal){

    console.log(skillVal)
    document.getElementById('closeModal').click()
    if(this.isAssessment == 'Course') {
      this.router.navigate(['pgm/employee/recommendedCourse', skillVal])
    } else if(this.isAssessment == 'Assessment') {
      this.router.navigate(['coach/employee/recommendedAssessment/', skillVal,this.empData.userInfoMstrId])
    } else {

    }
  }

  getCoachEmployees(Id) {
    Promise.all([
      this.AuthService.getRecommendedCourses(Id,''),
      this.AuthService.getAllEmployeesForCoach(Id)]
    )
      .then(arr => {
        console.log(arr, 'Array:completeresponse');
        
        this.employeeRecommendedCourses(arr)
        const courseRecommend = arr[0];
        const employeeList = arr[1];
        const listAllEmp = [];
        const recommendEmployee = [];
        const AllCourses = [];
        const eventDetails = [];
        const allRecommendedCoures = [];

        employeeList.forEach(item => {
          if (item.infoDtls.userInfoMstr.pgCourseEmployeeMapping.length !== 0 ) {
            console.log(item.infoDtls.userInfoMstr.pgCourseEmployeeMapping.length);
            if (!item.infoDtls.pgExperienceLevel) {
              item.infoDtls.pgExperienceLevel = {experienceLevel: ''};
            }
            if (!item.infoDtls.jobId) {
              item.infoDtls.jobId = '';
            }
            item.infoDtls.userInfoMstr.pgCourseEmployeeMapping.forEach(course => {
              AllCourses.push(course);
            });
            listAllEmp.push(item);
          }
        });

        Object.keys(courseRecommend).forEach(function (key) {
          for (const emp of listAllEmp) {
            if (key.toString() === emp.infoDtls.userInfoMstr.userInfoMstrId.toString()) {
              emp.infoDtls.userInfoMstr.pgCourseEmployeeMapping.courseId = courseRecommend[key];
              recommendEmployee.push(emp);
              console.log(recommendEmployee, 'recommendEmployee');
              courseRecommend[key].forEach(course => {
                allRecommendedCoures.push(course);
              });
            }
          }
        });

        AllCourses.forEach(allCourse => {
          let usr;
          usr = listAllEmp.filter(function (item, index, array) {
            return (item.infoDtls.userInfoMstr.userInfoMstrId === allCourse.userInfoMstrId);
          }),
            allCourse.courseDetails = allRecommendedCoures.filter(function (item, index, array) {
              return (item.pgCourseDetails.courseDetailsId === allCourse.courseId);
            });
          allCourse.evenDetails = listAllEmp.filter(function (item, index, array) {
            item.evenDetails.forEach(event => {
              return (item.courseId === allCourse.courseId);
            });
          });
          allCourse.userDetails = usr[0];
        });

        AllCourses.forEach(usr => {
          usr.userDetails.evenDetails.forEach(evnt => {
            if (  usr.courseId === evnt.courseId) {
              usr.evenDetails.push(evnt);
            }
          });
        });

        this.registeredCandidates = _.reverse(_.sortBy(AllCourses, ['updatedDt']));

        console.log(this.registeredCandidates, 'this.registeredCandidates');

        this.CFLANDING = true;
        this.listCandidates = this.registeredCandidates;

        this.primarySkillEvalCandidates = [];
        this.techUseCaseEvalCandidate = [];
        this.bussUseCaseEvalCandidate = [];

        for (const value of this.registeredCandidates){
          if (value.evenDetails.length !== 0) {
            if ( value.courseStatus === 'METTL_SCHEDULED' ||
              value.courseStatus === 'METTL_REVIEW' ||
              value.courseStatus === 'COURSE_COACH_ASSIGNED' ||
              value.courseStatus === 'METTL_COACH_ASSIGNED' ||
              value.courseStatus === 'METTL_APPROVED' ||
              value.courseStatus === 'METTL_REJECTED' ) {
              console.log('value.courseStatus', value.courseStatus);

              this.primarySkillEvalCandidates.push(value);
              this.primarySkillCandidateCount = this.primarySkillEvalCandidates.length;

            } else if ( value.courseStatus === 'MINI_PG_STARTED'  ||
              value.courseStatus === 'MINI_PG_COMPLETED' ||
              value.courseStatus === 'MINI_PG_COACH_APPROVED' ||
              value.courseStatus === 'MINI_PG_COACH_REJECTED' ) {

              this.techUseCaseEvalCandidate.push(value);
              this.techUseCaseCandidateCount = this.techUseCaseEvalCandidate.length;

            } else if (value.courseStatus === 'MAIN_PG_STARTED' ||
              value.courseStatus === 'MAIN_PG_MANAGER_APPROVED' ||
              value.courseStatus === 'MAIN_PG_COMPLETED' ||
              value.courseStatus === 'MAIN_PG_MANAGER_REJECTED' ||
              value.courseStatus === 'MAIN_PG_COACH_REVIEWED') {

              this.bussUseCaseEvalCandidate.push(value);
              this.bussUseCaseCandidateCount = this.bussUseCaseEvalCandidate.length;
            } else {
              const noCandidatesRecord = 'No Candidates Record found';
            }
          }
        }
        this.filterprimarySkillEvalCandidates = this.primarySkillEvalCandidates;
        this.filtertechUseCaseEvalCandidate = this.techUseCaseEvalCandidate;
        this.filterbussUseCaseEvalCandidate = this.bussUseCaseEvalCandidate;
        this.loader = false;
      }).catch (err => {
      console.log('Error for this :', err);
    });

    console.log(Id, 'All Req Body Dataaaaaaaa');
  }


  /**
   * This is for Recommended Course For Particular Employee
   * **/

  employeeRecommendedCourses(arr){



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

    let employeeRecommendCourse = []

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

    //
    console.log(employeeList,'list of employeeee');

    employeeList.forEach(item =>{

      if (item.infoDtls.userInfoMstr.pgCourseEmployeeMapping.length != 0 ){

        if(!item.infoDtls.pgExperienceLevel){

          item.infoDtls.pgExperienceLevel = {experienceLevel:null}
        }
        if(!item.infoDtls.jobId){

          item.infoDtls.jobId = null
        }

        item.infoDtls.userInfoMstr.pgCourseEmployeeMapping.forEach(course => {

          AllCourses.push(course)

        })
        listAllEmp.push(item)
      }

    });

    console.log(AllCourses,"AllCourses");
    console.log(listAllEmp,"listAllEmp");
    console.log(courseRecommend,"courseRecommend");

    Object.keys(courseRecommend).forEach(function (key) {
      for(let emp of listAllEmp) {
        if(key.toString() == emp.infoDtls.userInfoMstr.userInfoMstrId.toString()){

          let rc =[]

          for(var courseStatus of courseRecommend[key]){

            for (var mapCourse of emp.infoDtls.userInfoMstr.pgCourseEmployeeMapping){

              if(mapCourse.courseId == courseStatus.pgCourseDetails.courseDetailsId){

                if(mapCourse.courseStatus == 'COURSE_COACH_ASSIGNED' || mapCourse.courseStatus == 'COURSE_STARTED' || mapCourse.courseStatus == 'COURSE_COMPLETED' ) {

                  rc.push(Object.assign({}, courseStatus, mapCourse))
                }

              }

            }

          }
          employeeRecommendCourse.push({userDetails:emp.infoDtls,recommendedCourse:rc,fullName:emp.infoDtls.fullName})

          recommendEmployee.push(emp)

          console.log(key.toString(),emp.infoDtls.userInfoMstr.userInfoMstrId.toString(),"recommendEmployee");

          courseRecommend[key].forEach(course => {
            allRecommendedCoures.push(course)
          })

        }
        else {
        }
      }
    });

    console.log(employeeRecommendCourse,"employeeRecommendCourse");

    this.recommendCourseEmployee = employeeRecommendCourse

  }

  goToEventDetails($event){
    this.router.navigate(['coach/employee',$event]);
  }




  callMe() {
    this.userIcon = 'logout';
    console.log('callme');
  }

  Intials(cString) {
    if (cString) {
      return cString.replace(/\W*(\w)\w*/g, '$1').toUpperCase();
    }
  }

  getSubstring(text) {
    if (text) {
      return text.substring(0, 3);
    }
  }

  getTrim(text) {
    return text.substring(6);

  }

  goToEmployeeDetails($event) {
    const val = this.EmployeeCourseIdService.getEmployeeIdCourse();
    this.router.navigate(['coach/employee', val.userinfoMastrId]);
   // this.router.navigate(['coach/employeeDetails',val.userinfoMastrId,val.courseId]);
  }

  scheduleMettl($event) {
    this.router.navigate(['coach/employee', $event]);
   // this.router.navigate(['coach/employeeDetails',$event]);
  }

  filterBusiness(filterId) {
    if (filterId === 'all' ) {
      this.bussUseCaseEvalCandidate = this.filterbussUseCaseEvalCandidate;
    } else if (filterId === 'inProgress') {
      this.bussUseCaseEvalCandidate = this.filterbussUseCaseEvalCandidate.filter(function(item, index, array){
        return (item.courseStatus === 'MAIN_PG_STARTED' || item.courseStatus === 'MAIN_PG_COMPLETED' || item.courseStatus === 'MAIN_PG_COACH_ASSIGNED');
      });
    } else if (filterId === 'evaluation') {
      this.bussUseCaseEvalCandidate = this.filterbussUseCaseEvalCandidate.filter(function(item, index, array){
        return (item.courseStatus === 'MAIN_PG_COMPLETED' || item.courseStatus === 'MAIN_PG_COACH_REVIEWED');
      });
    } else if (filterId === 'completed') {
      this.bussUseCaseEvalCandidate = this.filterbussUseCaseEvalCandidate.filter(function(item, index, array){
        return (item.courseStatus === 'MAIN_PG_MANAGER_APPROVED' || item.courseStatus === 'MAIN_PG_MANAGER_REJECTED');
      });
    }
  }

  filterTechnical(filterId) {
    if (filterId === 'all' ) {
      this.techUseCaseEvalCandidate = this.filtertechUseCaseEvalCandidate;
    } else if (filterId === 'inProgress') {
      this.techUseCaseEvalCandidate = this.filtertechUseCaseEvalCandidate.filter(function(item, index, array){
        return (item.courseStatus === 'MINI_PG_STARTED' || item.courseStatus === 'MINI_PG_COMPLETED');
      });
    } else if (filterId === 'evaluation') {
      this.techUseCaseEvalCandidate = this.filtertechUseCaseEvalCandidate.filter(function(item, index, array){
        return (item.courseStatus === 'MINI_PG_COMPLETED');
      });
    } else if (filterId === 'completed') {
      this.techUseCaseEvalCandidate = this.filtertechUseCaseEvalCandidate.filter(function(item, index, array){
        return (item.courseStatus === 'MINI_PG_COACH_APPROVED' || item.courseStatus === 'MINI_PG_COACH_REJECTED');
      });
    }
  }

  filterPrimary(filterId) {
    if (filterId === 'all' ) {
      this.primarySkillEvalCandidates = this.filterprimarySkillEvalCandidates;
    } else if (filterId === 'notScheduled') {
      this.primarySkillEvalCandidates = this.filterprimarySkillEvalCandidates.filter(function(item, index, array){
        return (item.courseStatus === 'METTL_COACH_ASSIGNED' );
      });
    } else if (filterId === 'inProgress') {
      this.primarySkillEvalCandidates = this.filterprimarySkillEvalCandidates.filter(function(item, index, array){
        return (item.courseStatus === 'METTL_SCHEDULED' );
      });
    } else if (filterId === 'evaluation') {
      this.primarySkillEvalCandidates = this.filterprimarySkillEvalCandidates.filter(function(item, index, array){
        return (item.courseStatus === 'METTL_REVIEW' );
      });
    } else if (filterId === 'completed') {
      this.primarySkillEvalCandidates = this.filterprimarySkillEvalCandidates.filter(function(item, index, array){
        return (item.courseStatus === 'METTL_APPROVED' || item.courseStatus === 'METTL_REJECTED' );
      });
    }
  }

  updateCandidateStatus() {
    const obj = this.EmployeeCourseIdService.getEmployeeApproveRejectData();
    this.AuthService.employeeStatusUpdate({userInfoMstrId: obj.userInfoMstrId, courseId: obj.courseId, status: obj.status}).then( responseData => {
      const responseDataCheck = responseData;
      if (responseData['status'] === 'success') {

        /*
        if (this.updateemployeeStatus.status == 'METTL_APPROVED') {
           this.toastr.success("Employee PRIMARY SKILL EVALUATION APPROVED ");
        } else if(this.updateemployeeStatus.status == 'METTL_REJECTED'){
          this.toastr.success("Employee PRIMARY SKILL EVALUATION REJECTED");
        }
        */

      } else {
        console.log(responseData, 'Else case Canditates Approval ');
      }
    }).catch(err => {
      console.log(err);
    });
  }

  logout() {
    this.localStorageService.clearAll();
    localStorage.clear();
    this.router.navigate(['']);
  }

}
