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-recommended-course',
  templateUrl: './pgm-recommended-course.component.html',
  styleUrls: ['./pgm-recommended-course.component.scss']
})
export class PgmRecommendedCourseComponent 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
  };
  courseFilter: any = { courseName: '' };
  statusOf = 'beforeRecommended';
  // statusOf = 'afterRecommended';
  imageUrl: string = 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['id']
    )

    if (!this.UserID || this.UserID == null) {
      this.router.navigate(['pgm/landing/employee']);
    }
    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.employeeHttpService.getCourseBySkillId(this.UserID).takeUntil(this.$destroyed)
        .subscribe(data => {

          console.log(data, 'getCourseBySkillId')
          this.courses = data.mostPopularCourses;
          this.courses = this.courses.map(course => course.pgCourseDetails);

          this.recommendedCourses = data.topSpecCourses;



          console.log(this.courses, 'most course');
          console.log(this.recommendedCourses, 'top course');
        });

    }

  }


  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)
    }

  }


  keySearch(param) {

    console.log(param, 'param')

    if (param) {
      this.employeeHttpService.searchEmployee({ filterParam: param }).takeUntil(this.$destroyed)
        .subscribe(data => {

          console.log(data, 'SearchEmployee');

          this.empLists = data.userList
        })
    } else {
      this.empLists = []
    }
  }

  addCourseToUser() {
    console.log('Done Click');

    if (this.selectedCourses.length == 0) {
      this.toastr.success('Please Select Course');

    }
    else if (this.selectedEmployee == 0) {
      this.toastr.success('Please Select Employee');

    }
    else {

      console.log(this.selectedEmployeeDetails);
      console.log(this.selectedCourses);

      let reqObj = []
      let eventObj = { courseDetails: [] }
      let selCourse = []

      var d = new Date();
      d.setMonth(d.getMonth() + 1);
      var timestamp = d.getTime();

      this.selectedCourses.forEach(course => {

        reqObj.push({ userId: this.selectedEmployee.userInfoMstr.userInfoMstrId, courseId: course.courseId, dueDate: timestamp })
        eventObj.courseDetails.push({ userInfoMstrId: this.selectedEmployee.userInfoMstr.userInfoMstrId, courseId: course.courseId, assessment: course.assessment, isGroupCourse: false })

      });

      this.selectedCoursesDetails.forEach(course => {
        this.selectedEmployeeDetails.forEach(employee => {
          if (course.assessment == true) {
            course['candidate'] = employee
            course['selected'] = false
            this.selectedCoursesEmployeeDetails.push(course)
          }
        });
      });

      console.log(reqObj, 'reqobj')
      console.log(eventObj, 'eventObj')
      console.log(this.selectedCoursesEmployeeDetails, 'selectedCoursesDetails')

      this.AuthService.addMultiUserCourses(reqObj).then(resp => {

        console.log(resp)

        if (resp.status == 'success') {


          this.AuthService.addEmployeeEventDetails(eventObj).then(responceData => {

            console.log(responceData)
            console.log(this.selectedCoursesEmployeeDetails, 'selectedCoursesEmployeeDetails')

            if (this.selectedCoursesEmployeeDetails.length == 0) {
              this.toastr.success(resp.message);
              this.router.navigate(['pgm/landing/employee']);
            }
            else {
              this.statusOf = 'afterRecommended';

            }


          }).catch(error => {

            console.log(error)
          })


          // this.router.navigate(['pgm/landing/employee'])
        }
        else {
          this.statusOf = 'afterRecommended';
          this.toastr.error(resp.message);
        }

      }).catch(err => {
        console.log(err);
        this.toastr.error(err.message);
      })

    }


  }


  selectCourseEmp(course: any = {}) {

    console.log(course);
    if (course.selected) {
      course.selected = false;
      this.courseEmployeLists = this.courseEmployeLists.filter(item => item.courseDetailsId !== course.courseDetailsId);
    } else {
      course.selected = true;
      this.courseEmployeLists.push(course)
    }

    console.log(this.courseEmployeLists, 'courseEmployeLists')
  }

  selectCourse(course: any = {}) {
    if (course.selected) {
      course.selected = false;
      this.selectedCourses = this.selectedCourses.filter(item => item.courseId !== course.courseDetailsId);
    } else {
      course.selected = true;
      this.selectedCourses.push({ 'courseId': course.courseDetailsId, "assessment": course.assessment });
      this.selectedCoursesDetails.push(course)
    }
    console.log(this.selectedCourses, 'selectedCourses');
    console.log(this.selectedCoursesDetails, 'selectedCoursesDetails');
    //   this.employeeWizardService.setCourses(this.selectedCourses);
  }



  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,
        "assessment": true,
        "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/employee']);

    }).catch(err => {

      console.log(err, 'error')

    })

  }

}
