import { Component, OnInit, ViewEncapsulation, ViewChild, ElementRef } from '@angular/core';
import { AuthService } from '../../../services/auth.service';
import {Router} from '@angular/router';
import {LocalStorageService} from "angular-2-local-storage";
import {NavigationService} from "../../../services/navigation/navigation.service";
import {ToastsManager} from "ng2-toastr";
import {PgmEmployeeDashBoardComponent} from "../pgm-employee-dash-board/pgm-employee-dash-board.component";
import {Subject} from "rxjs/Subject";
import { NavBarService } from "../../pgm.service";
import {CoachCandidateEvaluationService} from "../../../coach/shared/service/coach-candidate-evaluation.service";
import { UserInfo } from '../../../models/userInfo.model';
import {Statuscount} from "../../../employee/employee-newdashboard/employee-task/employee-task.component";
import _ from "lodash";
import { environment } from '../../../../environments/environment.dev';

@Component({
  selector: 'app-pgm-bny-employee-landing',
  templateUrl: './pgm-bny-employee-landing.component.html',
  styleUrls: ['./pgm-bny-employee-landing.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class PgmBnyEmployeeLandingComponent implements OnInit {
  @ViewChild('searchword') searchword: ElementRef;
  imagelink: string;
  records: any;
  recordscopy: any;
  courserecords: any;
  allstatuscourserecords: any;
  allstatuscourserecordscopy: any;
  AllcourserecordsCount: number;
  primaryusecase: any;
  technicalusecase: any;
  businessusecase: any;

  primaryusecasecopy: any;
  technicalusecasecopy: any;
  businessusecasecopy: any;
  learningPathcopy: any;
  courseListcopy: any;

  skills: any;
  statuscount: Statuscount;
  primarycount: number;
  technicalcount: number;
  businesscount: number;
  empData: UserInfo;
  filterword: string;
  previousfilterword: string;
  filterclickCount: number = 0;
  activefilter: string;

  courseList = [];
  learnPathList = [];
  primaryList = [];
  technicalList = [];
  businessList = [];
  pgmNames =[];

  img_path_prefix = environment.imageUrl+'/assets/img/employee/dashboard/home/';
  img_path_suffix = '.png';
  navItems = [
    { title: 'Course and Assessment', link: '/talent-transformation/employee/CourseAndAssessment/1' },
    { title: 'Learning Path', link: '/talent-transformation/employee/CourseAndAssessment/2' },
  ];
  filterCol = false;
  selectedPgms: any = [];
  checked:boolean;
  imageUrl: string = environment.imageUrl;
  constructor(protected localStorageService: LocalStorageService,
              private AuthService: AuthService,
              private router: Router,
              private navigate: NavigationService,
              private navBarService: NavBarService,
              private toastr: ToastsManager,
              private CoachCandidateEvaluationService: CoachCandidateEvaluationService,
              ) {

    this.navBarService.setCurrentPage(0);
    this.CoachCandidateEvaluationService.setProperActiveTab(2);
    this.empData = this.localStorageService.get('userInfo');
    this.getAllSkills();
    this.getAllAssessment(this.empData.email);
    this.getAllRecommendedCourseEmployee(this.empData.email);
    this.getAllPgms();
  }

  ngOnInit() {
    this.activefilter = 'initial';
    this.imagelink = environment.imageUrl+'/assets/img/employee/newdashboard/';
    this.statuscount = {
      'Overdue': 0,
      'ToDo': 0,
      'InProgress': 0,
      'UnderReview': 0,
      'ReviewCompleted': 0,
      'Done': 0
    };
    this.primarycount = 0;
    this.technicalcount = 0;
    this.businesscount = 0;
    this.allstatuscourserecords = [];
    this.AllcourserecordsCount = 0;

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

    this.selectedPgms.push(this.empData.userInfoMstrId);
  }

  closeFilter() {
    console.log("Filter close clicked")
    this.filterCol = !this.filterCol;
  }

  resetFilters(){
    this.selectedPgms.splice(0);
    console.log(this.selectedPgms);
    this.pgmNames = [];
  //  !this.empData.userInfoMstrId;
    this.selectedPgms.push(this.empData.userInfoMstrId);
    // the loged in pgm will not be cleared after reset.
    this.getAllRecommendedCourseEmployee(this.selectedPgms);
  }
  getrecord(item) {
    console.log(item);
  }

  goToEmployeeDetails($event) {
    this.router.navigate(['talent-transformation/employee', $event]);
  }

  /* Get All events for All Employees*/

  getAllAssessment(userId) {
    // this.primaryList = [];
    // this.technicalList = [];
    // this.businessList = [];
    // this.learnPathList = [];

    this.AuthService.getAllEmployeeAssessmentsNew(userId).then(resp => {
      console.log(resp);
      //this.courseList = resp['Launch Course'];
      this.technicalList = resp['Launch Technical Use Case'];
      this.businessList = resp['Launch Business Use Case'];
      this.primaryList = resp['Launch Primary Skills Evaluation'];
      this.learnPathList = resp['Learning Path'];

      this.primaryusecasecopy = this.primaryList;
      this.technicalusecasecopy = this.technicalList;
      this.businessusecasecopy = this.businessList;
      this.learningPathcopy = this.learnPathList;

     // this.getStatusCount(this.courseList,'course');
      this.getStatusCount(this.technicalList, 'assessment');
      this.getStatusCount(this.businessList, 'assessment');
      this.getStatusCount(this.primaryList, 'assessment');
      this.getStatusCount(this.learnPathList, 'learnPath');

    }).catch(err => {
      console.log(err);
    });
  }

  /*get ALL Course For Employees*/

  getAllRecommendedCourseEmployee(userId){
    Promise.all([

      this.AuthService.getRecommendedCourses(userId,this.empData.userInfoMstrId),
      this.AuthService.getAllListOfEmployee(userId,{})]
    )
      .then(arr => {
        console.log(arr[0],'RecommendedCourses')
        console.log(arr[1],'All EMPLOYeee')
        this.AllCourseOfEmployees(arr[0], arr[1]);

      }).catch (err => {
      console.log("Error for this :",err)
    })
  }


  /**
   * This is for ALL Course for All Employees
   * **/

  AllCourseOfEmployees(courses, empList) {
    let CL = [];
    Object.keys(courses).forEach(function (key) {
      for (let emp of empList) {
        if (key.toString() == emp.userInfoMstrId.toString()) {
          CL.push({'userDetails': emp, 'courseList': courses[key]});
        } else {
        }
      }
    });
    this.courseList = CL
    this.courseListcopy = this.courseList;
    this.getStatusCount(this.courseList, 'course');
    console.log( this.courseList);
  }

  /*THIS IS STATUS COUNT FUNCTION*/
  getStatusCount(record, status) {
    if (status === 'assessment') {
      record.forEach(event => {
        event.employeeEvents.forEach(obj => {
          if (obj.assessmentStatus === 'ASSIGNED') {
          this.statuscount.ToDo += 1;
          }
          if (obj.assessmentStatus === 'INPROGRESS') {
            this.statuscount.InProgress += 1;
          }
          if (obj.assessmentStatus === 'REVIEW_PENDING') {
            this.statuscount.InProgress += 1;
          }
          if (obj.assessmentStatus === 'UNDER_REVIEW') {
          
            this.statuscount.UnderReview += 1;
          }
          if (obj.assessmentStatus === 'REVIEW_COMPLETED') {
            this.statuscount.ReviewCompleted += 1;
          }
          if (obj.assessmentStatus === 'OVERDUE') {
            this.statuscount.Overdue += 1;
          }
          if (obj.assessmentStatus === 'DONE') {
            this.statuscount.Done += 1;
          }
        });
      });
    }
    if (status === 'learnPath') {
      record.forEach(event => {
        event.empLpList.forEach(obj => {
          if (obj.userStatus === 'TODO') {
          this.statuscount.ToDo += 1;
        }
        if (obj.userStatus === 'INPROGRESS') {
          this.statuscount.InProgress += 1;
        }
        if (obj.userStatus === 'OVERDUE') {
          this.statuscount.Overdue += 1;
        }
        if (obj.userStatus === 'DONE') {
          this.statuscount.Done += 1;
        }
      });
      });
    }
    if (status === 'course') {
      record.forEach(event => {
        event.courseList.forEach(obj => {
          if (obj.status === 'Open') {
          this.statuscount.ToDo += 1;
        }
        if (obj.status === 'In Progress') {
          this.statuscount.InProgress += 1;
        }
        if (obj.status === 'Overdue') {
          this.statuscount.Overdue += 1;
        }
        if (obj.status === 'DONE') {
          this.statuscount.Done += 1;
        }
      });
      });
    }
  }

  getAllCourse(id) {
    this.AuthService.getEmployeeAllCourse(id).then(resp => {
      this.courserecords = resp.userCourseMapping;
      if (this.courserecords['In Progress'] !== undefined) {
        const inProgressCourse = this.courserecords['In Progress'].length > 0 && this.courserecords['In Progress'].map(obj => this.allstatuscourserecords.push(obj));
      }
      if (this.courserecords.Completed !== undefined) {
        const completedCourse = this.courserecords.Completed.length > 0 && this.courserecords.Completed.map(obj => this.allstatuscourserecords.push(obj));
      }
      if (this.courserecords.Open !== undefined) {
        const openCourse = this.courserecords.Open.length > 0 && this.courserecords.Open.map(obj => this.allstatuscourserecords.push(obj));
      }
      if (this.courserecords.Overdue !== undefined) {
        const overdueCourse = this.courserecords.Overdue.length > 0 && this.courserecords.Overdue.map(obj => this.allstatuscourserecords.push(obj));
      }

      this.allstatuscourserecordscopy = [...this.allstatuscourserecords];
      this.AllcourserecordsCount = this.allstatuscourserecords.length;
      this.getCount(this.allstatuscourserecords);
      console.log(this.allstatuscourserecords);
    }).catch(err => {
      console.log(err);
    });
  }

  getCount(record) {
    record.map(obj => {
      const status = obj.status.trim();
      if (status === 'Overdue') { this.statuscount.Overdue += 1; }
      if (status === 'Open') { this.statuscount.ToDo += 1; }
      if (status === 'Completed') { this.statuscount.Done += 1; }
      if (status === 'In Progress') { this.statuscount.InProgress += 1; }
    });
  }

  getCountAssessment(record) {
    record.map(obj => {
      if (obj.assessmentStatus === 'ASSIGNED') { this.statuscount.ToDo += 1; }
      if (obj.assessmentStatus === 'INPROGRESS') { this.statuscount.InProgress += 1; }
      if (obj.assessmentStatus === 'REVIEW_PENDING') { this.statuscount.InProgress += 1; }
      if (obj.assessmentStatus === 'UNDER_REVIEW') { this.statuscount.UnderReview += 1; }
      if (obj.assessmentStatus === 'REVIEW_COMPLETED') { this.statuscount.ReviewCompleted += 1; }
      if (obj.assessmentStatus === 'DONE') { this.statuscount.Done += 1; }
    });
  }

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

  getAllPgms(){
    this.AuthService.getAllPgMgrs().then(resp => {
      //  console.log(resp, 'getAllSkills');
      this.pgmNames  = resp;
      console.log(this.pgmNames,'getAllPGM ');
    }).catch(err => {
      console.log(err);
    });
  }

  filterdata() {
    console.log(this.records);
    this.getCountAssessment(this.records);
    this.primaryusecase = this.records.filter(obj => obj.eventMstrId === 1);
    this.technicalusecase = this.records.filter(obj => obj.eventMstrId === 2);
    this.businessusecase = this.records.filter(obj => obj.eventMstrId === 3);
    this.primaryusecasecopy = this.primaryusecase;
    this.technicalusecasecopy = this.technicalusecase;
    this.businessusecasecopy = this.businessusecase;
    this.primarycount = this.primaryusecase.length;
    this.technicalcount = this.technicalusecase.length;
    this.businesscount = this.businessusecase.length;
  }

  insearch(searchword) {
    const kw = searchword;
    if (kw.length >= 2) {
      this.activefilter = '';
      this.courseList = this.courseListcopy.filter(x => {
      return  x.userDetails.fullName.toLowerCase().includes(kw.toLowerCase())
      });
      this.learnPathList = this.learningPathcopy.filter(x => {
       return x.userDetails.fullName.toLowerCase().includes(kw.toLowerCase())
      });
      this.primaryList = this.primaryusecasecopy.filter(x =>{
          return  x.userDetails.fullName.toLowerCase().includes(kw.toLowerCase())
    });
      this.technicalList = this.technicalusecasecopy.filter(x => {
        return x.userDetails.fullName.toLowerCase().includes(kw.toLowerCase())
      });
      this.businessList = this.businessusecasecopy.filter(x => {
        return x.userDetails.fullName.toLowerCase().includes(kw.toLowerCase())
      });
    }  
    else {
      this.activefilter = '';
      this.courseList = this.courseListcopy;
      this.primaryList = this.primaryusecasecopy;
      this.technicalList = this.technicalusecasecopy;
      this.businessList = this.businessusecasecopy;
      this.learnPathList = this.learningPathcopy;
    }
  }

  statusfilter(data) {
    console.log(data);
    console.log(this.getStatus(data))
    this.activefilter = data;
    let courseStatus = this.getCourseStatus(data);    
    let LPStatus = this.getLPStatus(data);    
    data = this.getStatus(data);
    this.searchword.nativeElement.value = '';

  
    let lp = [];
    let course = [];
    let primary = [];
    let technical = [];
    let business = []

        
     /** course Path filter */
     this.courseListcopy.forEach(item => {
      let list ={userDetails:item.userDetails, courseList:[]}
      item.courseList.filter(function (item, index, array) {
      if (item.status === courseStatus){
        list.courseList.push(item)
      }
    })
    course.push(list)
  })
  this.courseList = course.filter(item => {
    return item.courseList.length !== 0
  })


     /** Learning Path filter */
     this.learningPathcopy.forEach(item => {
      let LPlist ={userDetails:item.userDetails, empLpList:[]}
      item.empLpList.filter(function (item, index, array) {
      if (item.userStatus === LPStatus){
        LPlist.empLpList.push(item)
      }
    })
    lp.push(LPlist)
  })
  this.learnPathList = lp.filter(item => {
    return item.empLpList.length !== 0
  })
    
 /** Primary filter */
 this.primaryusecasecopy.forEach(item => {
  let list ={userDetails:item.userDetails, employeeEvents:[]}
  item.employeeEvents.filter(function (item, index, array) {
  if (item.assessmentStatus === data){
    list.employeeEvents.push(item)
  }
})
primary.push(list)
})
this.primaryList = primary.filter(item => {
return item.employeeEvents.length !== 0
})


 /** Technical  filter */

 this.technicalusecasecopy.forEach(item => {
  let list ={userDetails:item.userDetails, employeeEvents:[]}
  item.employeeEvents.filter(function (item, index, array) {
  if (item.assessmentStatus === data){
    list.employeeEvents.push(item)
  }
})
technical.push(list)
})
this.technicalList = technical.filter(item => {
return item.employeeEvents.length !== 0
})

  /** Business  filter */

  this.businessusecasecopy.forEach(item => {
    let list ={userDetails:item.userDetails, employeeEvents:[]}
    item.employeeEvents.filter(function (item, index, array) {
    if (item.assessmentStatus === data){
      list.employeeEvents.push(item)
    }
  })
  business.push(list)
  })
  this.businessList = business.filter(item => {
  return item.employeeEvents.length !== 0
  })

    
  }

  getStatus(data) {
    var json = {
      "Done" : "DONE",
      "Review Completed" : "REVIEW_COMPLETED",
      "Under Review" : "UNDER_REVIEW",
      "In Progress" : "INPROGRESS",
      "To Do" : "ASSIGNED",
      "Overdue" : "OVERDUE",
    }
    return json[data];
  }

  getLPStatus(data) {
    var json = {
      "Done" : "DONE",
      "Review Completed" : "REVIEW_COMPLETED",
      "Under Review" : "UNDER_REVIEW",
      "In Progress" : "INPROGRESS",
      "To Do" : "TODO",
      "Overdue" : "OVERDUE",
    }
    return json[data];
  }

  getCourseStatus(data) {
    var json = {
      "In Progress" : "INPROGRESS",
      "To Do" : "Open",
      "Overdue" : "Overdue",
    }
    return json[data];
  }

  nameFilter(name){
    console.log("PGM name -- ",name);
   // console.log("this.selectedPgms --- ", this.selectedPgms);
   /* if(e.target.checked === true ){
    this.selectedPgms.push(name.userInfomstrId);
    }
    else{
      this.selectedPgms.splice(this.selectedPgms.indexOf(name.userInfomstrId), 1)
    }

    if (this.selectedPgms.length > 0){
      this.selectedPgms = this.selectedPgms;
    }
    else{
    this.selectedPgms = this.selectedPgms[0];
    }*/
    console.log("this.selectedPgms 2ndtime console --- ", this.selectedPgms);
    this.ngOnInit();
    this.getAllRecommendedCourseEmployee(name);
    this.getAllAssessment(name);
  }
}
export interface Statuscount {
  'Overdue': number;
  'ToDo': number;
  'InProgress': number;
  'UnderReview': number;
  'ReviewCompleted': number;
  'Done': number;
}
