import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import { AuthService } from 'app/services/auth.service';
import { LocalStorageService } from 'angular-2-local-storage';
import { Router, ActivatedRoute } from '@angular/router';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { URLSearchParams } from '@angular/http';
import { NavBarService } from 'app/pgm/pgm.service';
import { DomSanitizer } from '@angular/platform-browser';
import { Course, CourseListTabs, createCourseListTabs, UserCourseMapping} from 'app/models/capability-transformation/course-list.model';
import _ from 'lodash';
import {isType} from "@angular/core/src/type";
import {Statuscount} from "../../employee/employee-newdashboard/employee-task/employee-task.component";
import {EmployeeHttpService} from "../../services/employee/employee-http.service";
import { environment } from '../../../environments/environment.dev';
@Component({
  selector: 'app-pgm-employee-details',
  templateUrl: './pgm-employee-details.component.html',
  styleUrls: ['./pgm-employee-details.component.scss', './../../employee/employee-newdashboard/employee-task/employee-task.component.scss',
  ],
 // encapsulation: ViewEncapsulation.None
})

export class PgmEmployeeDetailsComponent implements OnInit {

  UserID: any;
  candt: any;
  PGMCandidateDtls = false;
  masterSkills: any[];
  userData: {
    userInfoDtlsId: string,
    adId: string,
    fullName: string,
    email: string,
    location: string,
    profileName: string,
    profileId: string,
    linkedInId: string,
    googleId: string,
    facebookId: string,
    city: string,
    country: string;
    otherDesc: string,
    pgUserInfoMstr: {
      firstNm: string,
      fullName: string,
      email: string,
      status: any,
      userInfoMstrId: string,
      pgLocation: {
        city: string
      }
      pgUserSkillMapping: [{
        pgSkillTrackDtls: {
          pgSkillTrackMstr: {
            description: string,
            skillTrackName: string
          },
          description: string,
        },
      }]
    },
    experienceLevel: string,
    emailId: string,
    addressLine1: string,
    jobId: string,
    alternativeEmail: string,
    contactNumber: string,
    alternativeContact: string,
    governmentId: string,
  };
  empDtlsArrow = 'empDtls-arrow-selected';
  masterSkillIds = [];
  skillDetails: any[];
  empStatus = false;
  courses: any = [];
  coursesLists: CourseListTabs = createCourseListTabs();
  courseListNames = [];
  AllEvents = true
  AllLPs = false;
  allstatuscourserecords = [];
  allStatusLearningPathRecords = [];
  learningPathCount: number;
  allStatusLearningPathReservRecords: any;
  allstatuscourserecordscopy: any;
  AllcourserecordsCount: number;
  filterPrimaryusecase: any;
  filterTechnicalusecase: any;
  filterBusinessusecase: any;
  filterAllstatuscourserecords: any;
  filterAllStatusLearningPathRecords: any;
  primaryusecase = [];
  technicalusecase = [];
  businessusecase = [];
  primaryusecasecopy: any;
  technicalusecasecopy: any;
  businessusecasecopy: any;
  learningPathCollection: any;
  learningPathDetails: any;
  skills: any;
  statuscount: Statuscount;
  primarycount: number;
  technicalcount: number;
  businesscount: number;
  courserecords: any;
  records: any;
  recordscopy: any;
  useCaseData: any;
  selectedAssessmentName: any;
  selectedAssessmentStatus: any;
  reviewerFeedbacks = [];
  imageLink = environment.imageUrl+'/assets/img/employee/dashboard/assessment/';
  learningPathCardDetails = [];
  learningPathData = false;
  courseCollection = [];
  assessmentCollection: any;

  technicalAssList = []
  businessAssList = []
  primaryAssList = []

  imageUrl = environment.imageUrl;
  constructor(protected localStorageService: LocalStorageService,
              private AuthService: AuthService,
              private router: Router,
              private route: ActivatedRoute,
              private toastr: ToastsManager,
              private navBarService: NavBarService,
              private employeeHttpService: EmployeeHttpService,
              public sanitizer: DomSanitizer) {

    this.route.params.subscribe( params =>
      this.UserID = params['empId']
    );

    if (!this.UserID || this.UserID == null) {
      this.router.navigate(['talent-transformation/landing/employee']);
    } else {
      this.AuthService.getEmployeeTestDetails(this.UserID).then(resp => {
        resp = resp.pgUserInfoDtlsList[0];
        const response = resp;
        this.userData = resp;
        console.log(this.userData);

        if (!resp.pgExperienceLevel || resp.pgExperienceLevel === null || resp.pgExperienceLevel === undefined) {
          resp.pgExperienceLevel = {experienceLevel : ''};
        }

        this.candt = resp;
        this.PGMCandidateDtls = true;
        this.masterSkills = _.uniqBy(this.userData.pgUserInfoMstr.pgUserSkillMapping, 'pgSkillTrackDtls.pgSkillTrackMstr.description');

        this.masterSkills.forEach(usrSkills => {
          this.masterSkillIds.push(usrSkills.pgSkillTrackDtls.pgSkillTrackMstr.skillTrackMstrId);
        });

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

      this.getAllLearningPath(this.UserID);
      this.getAllAssessment(this.UserID);
      this.getAllCourse(this.UserID);
      this.getAllSkills();

      this.navBarService.setCurrentPage(5);
    }
  }

  ngOnInit() {
    this.primarycount = 0;
    this.technicalcount = 0;
    this.businesscount = 0;
    this.allstatuscourserecords = [];
    this.allStatusLearningPathRecords = [];
    this.AllcourserecordsCount = 0;
  }
  getSubstring(text) {
    if (text) {
      return text.substring(0, 3);
    }
  }

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

  goto(x) {
    if (x !== 'empDtls') {  this.router.navigate( ['talent-transformation/landing/employee']);
    } else {
     this.AllEvents = true;
      this.selectedAssessmentName = undefined;
      this.empDtlsArrow = 'empDtls-arrow-selected';
    }
  }


  hideSlidingBtn() {
  //  this.getBackErrow.emit(true);
  }

  report(assessment) {
  }

  /*SCORE TYPE CONVERSTION*/
  score(mark) {
    return  Number(mark);
  }

  filterdata() {
    console.log(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;
    console.log(this.primaryusecase, 'primaryusecase');
  }

  getAllAssessment(id) {
    this.AuthService.getEmployeeAssessmentStatus(id).then(resp => {
      this.records = resp;
      this.records.forEach(element => {
        if (element.assessmentStatus === 'REVIEW_PENDING') {
          element.assessmentStatus = 'INPROGRESS';
        }
      });
      this.recordscopy = [...resp];
      if (this.records) {
        this.filterdata();
      }
    }).catch(err => {
      console.log(err);
    });
  }

  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.getCountCourses(this.allstatuscourserecords);
      console.log(this.allstatuscourserecords);
    }).catch(err => {
      console.log(err);
    });
  }
  getAllLearningPath(userMasterId) {
    // OVERDUE, TODO, INPROGRESS, DONE
    console.log(userMasterId);
    this.employeeHttpService.getLearningPathOfEmp(userMasterId).subscribe(response => {
      this.learningPathCollection = response;
      if (this.learningPathCollection.INPROGRESS !== undefined) {
        const inProgressCourse = this.learningPathCollection.INPROGRESS.length > 0 && this.learningPathCollection.INPROGRESS.map(obj => this.allStatusLearningPathRecords.push(obj));
      } if (this.learningPathCollection.DONE !== undefined) {
        const completedCourse = this.learningPathCollection.DONE.length > 0 && this.learningPathCollection.DONE.map(obj => this.allStatusLearningPathRecords.push(obj));
      } if (this.learningPathCollection.TODO !== undefined) {
        const openCourse = this.learningPathCollection.TODO.length > 0 && this.learningPathCollection.TODO.map(obj => this.allStatusLearningPathRecords.push(obj));
      } if (this.learningPathCollection.OVERDUE !== undefined) {
        const overdueCourse = this.learningPathCollection.OVERDUE.length > 0 && this.learningPathCollection.OVERDUE.map(obj => this.allStatusLearningPathRecords.push(obj));
      }
     // this.getCountFromLearningPath(this.allStatusLearningPathRecords);
      this.allStatusLearningPathReservRecords = [...this.allStatusLearningPathRecords]
      console.log(response);
    }, (error) => {
      console.log(error);
    });
  }
  gotoLP(evnt) {
    console.log(evnt, 'learningPath Id');
    this.selectedAssessmentName = evnt.title;
    this.selectedAssessmentStatus = evnt.assessmentStatus;

    this.viewLearningPath(evnt.learningPathId);
  }



  viewLearningPath(id) {
    console.log(id);
    this.employeeHttpService.getLearningPathCardDetails(id).subscribe(response => {
      console.log(response);
      this.learningPathCardDetails = response.learningPath;
      this.learningPathData = true;
      this.AllEvents = false;
      this.empDtlsArrow = 'empDtls-arrow';
    }, (error) => {
      console.log(error);
    });
  }


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

  goToEventDetails(evnt) {
    console.log(evnt);
    if(evnt){
      this.selectedAssessmentName = evnt.title;
      this.getAssessmetDetails(evnt.eventId, evnt.title);
    }
  }

  getAssessmetDetails(eventDtlsId, AssessmentName) {

    this.AuthService.getEmployeeAssessmentDetails(
      {
        eventId: eventDtlsId,
      }).then(resp => {
      console.log(resp, "AssessmentDetails");
      console.log(resp.assessmentStatus);
      this.selectedAssessmentStatus = resp.assessmentStatus;
      if (resp.assessmentStatus === 'ASSIGNED' || resp.assessmentStatus === 'INPROGRESS') {
      } else {
        this.getReviewerDetails(eventDtlsId);
      }
      if (AssessmentName === 'Business Usecase Assessment') {
        this.useCaseData = resp.business[0];
      } else if (AssessmentName === 'Primary Assessment') {
        this.useCaseData = resp.primary[0];
      } else if (AssessmentName === 'Technical Usecase Assessment') {
        this.useCaseData = resp.technical[0];
      }
      this.AllEvents = false;
      this.empDtlsArrow = 'empDtls-arrow';

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


  getReviewerDetails(id) {

    this.AuthService.getReviewerDetails(id).then(response => {
       console.log('reviewData', response);

      this.reviewerFeedbacks = response.reviewerFeedback;

    }).catch(err => {
      console.log('Error Encounted while getting review details');
    });
  }

  getCountReviewer(list) {
    console.log(list);
    var result = list.filter(item => {
      return (item.status === 'REJECTED' || item.status === 'PASSED');
    });
    return result.length;
  }

  closeLP() {
    this.AllEvents = !this.AllEvents;
    this.selectedAssessmentName = undefined;
    this.empDtlsArrow = 'empDtls-arrow';
  }

}
export interface Statuscount {
  'Overdue': number;
  'ToDo': number;
  'InProgress': number;
  'UnderReview': number;
  'ReviewCompleted': number;
  'Done': number;
}
