import { PgCourseDetails } from './../../../../models/capability-transformation/course-list.model';
import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { LocalStorageService } from 'angular-2-local-storage';
import { Observable } from 'rxjs/Rx';
import { Subject } from 'rxjs/Subject';
import { Router } from '@angular/router';
import { EmployeeNavBarService } from 'app/employee/employee-dashboard/employee-nav-bar.service';
import { EmployeeCoursesSliderComponent } from 'app/employee/shared/employee-course-card/employee-course-card.component';
import { CapabilityTransformationHttpService } from 'app/services/capability-transformation/capability-transformation-http.service';
import { UserInfo } from 'app/models/userInfo.model';
import { UserCourseMapping, CourseListTabs, createCourseListTabs, Course, CourseCardType, CourseUpdatePayload, CourseStatus } from 'app/models/capability-transformation/course-list.model';
import { StatusCount, StatusCountDetails } from 'app/models/employee.model';
import { PrimarySkills, EventStatus } from 'app/models/assessment/assessment.model';
import { AssessmentHttpService } from 'app/services/assessment/assessment-http.service';
import { EmployeeCourseAssessmentResponse } from 'app/models/assessment/employee-assessment.model';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { CANDIDATE_STATUS_NAMES, CANDIDATE_STATUS_OBJECT } from 'app/models/candidateStatus';
import {AuthService} from '../../../../services/auth.service';
import { environment } from '../../../../../environments/environment.dev';
enum CourseListFilter {
  all = 'all',
  mandatory = 'mandatory',
  personal = 'personal'
}

@Component({
  selector: 'app-employee-dashboard-home-ct',
  templateUrl: './employee-dashboard-home-ct.component.html',
  styleUrls: ['./employee-dashboard-home-ct.component.css']
})
export class EmployeeDashboardHomeCTComponent implements OnInit, OnDestroy {
  private $destroyed = new Subject();
  private currentUser: UserInfo;
  public toggleHeaderStatus = false;
  @Input() courseCounters: StatusCount | null;
  @Input() primarySkills: PrimarySkills | null;

  public ct_tabs = [
    { id: CourseListFilter.all, name: 'All' },
    { id: CourseListFilter.mandatory, name: 'Mandatory' },
    { id: CourseListFilter.personal, name: 'My Interests' }
  ];
  public selectedTab = this.ct_tabs[0];

  courses: any = [];
  coursesLists: CourseListTabs = createCourseListTabs();
  courseListNames = [];
  imageUrl: string = environment.imageUrl;
  constructor(
    private coursesHttpService: CapabilityTransformationHttpService,
    private assessmentService: AssessmentHttpService,
    private localStorageService: LocalStorageService,
    private employeeNavBarService: EmployeeNavBarService,
    private router: Router,
    private AuthService: AuthService,
    private toastr: ToastsManager
  ) { }

  ngOnInit() {
    this.currentUser = this.localStorageService.get('userInfo');
    /*this.coursesHttpService.getUserCoursesDashboard(this.currentUser.userInfoMstrId).takeUntil(this.$destroyed)
    .subscribe(data => {*/

    /*TODO NEW ASSESSMENT FORMAT WILL CHANGE NEW FUNCTIONS*/
    Promise.all([
      this.AuthService.getEmployeeCourses(this.currentUser.userInfoMstrId),
      this.AuthService.getEmployeeAssessments(this.currentUser.userInfoMstrId)
    ])
      .then(arr => {
        console.log(arr)
        console.log(arr[1])

        let data = arr[0];
        let recommendedAssessment = arr[1].eventDetails;
        if (Object.keys(data.userCourseMapping).indexOf('Assessment') > -1) {
          const assessmentCourses = Object.assign(data.userCourseMapping.Assessment);
          assessmentCourses.map(course => {
          //  course['isType'] = 'course';
            this.getCourseAssessment(Object.assign(course.pgCourseDetails, course));
          });
          delete data.userCourseMapping.Assessment;
        }
        this.mapResponseToCourses(data.userCourseMapping);
        if (recommendedAssessment.length !== 0) {
          recommendedAssessment.forEach(assmt => {
            if( assmt.eventDtls.length !== 0) {
              assmt['isType'] = 'assessment';
              assmt['assessmentDtls'] = assmt.assessmentDetails;
              assmt['assessmentEvent'] = assmt.eventDtls;
              this.coursesLists.all.Assessment.courses.push(assmt);
            }
          })
        }
      })
    this.courseListNames = Object.keys(this.coursesLists.all).map( courseListName => this.coursesLists.all[courseListName].name);
  }

  getCourseAssessment(course: Course) {
    this.assessmentService.getEmployeeCourseAssessment(this.currentUser.userInfoMstrId, course.courseDetailsId)
    .finally(() => {
      this.coursesLists.all.Assessment.courses.push(course);
      if (course.recommended) {
        this.coursesLists.mandatory.Assessment.courses.push(course);
      } else {
        this.coursesLists.personal.Assessment.courses.push(course);
      }
    })
    .subscribe(
      (assessment: EmployeeCourseAssessmentResponse) => {
        course.assessmentDetails = assessment;
        /* Updating event status */
        const mettlStatus = course.assessmentDetails.employeeCourseDetails.courseStatus;
        if (mettlStatus in CANDIDATE_STATUS_OBJECT) {
          course.assessmentDetails.employeeEventDetails[2].eventSts = CANDIDATE_STATUS_OBJECT[mettlStatus].id >= CANDIDATE_STATUS_OBJECT[CANDIDATE_STATUS_NAMES.MINI_PG_COMPLETED].id ? EventStatus.COMPLETED : course.assessmentDetails.employeeEventDetails[2].eventSts;
          course.assessmentDetails.employeeEventDetails[3].eventSts = CANDIDATE_STATUS_OBJECT[mettlStatus].id >= CANDIDATE_STATUS_OBJECT[CANDIDATE_STATUS_NAMES.MAIN_PG_COMPLETED].id ? EventStatus.COMPLETED : course.assessmentDetails.employeeEventDetails[3].eventSts;
        }
      }
    );
  }

  /**
   * Adapt each course to Course interface
   * @description
   * The getUserCoursesDashboard response data is different from what is received on first wizard page by getCourseByCategory so it needs to be adapted
   * This function also fills each tab data
   * @public
   * @param {UserCourseMapping} userCourseMapping
   * @memberof EmployeeDashboardHomeCTComponent
  */
  mapResponseToCourses(userCourseMapping: UserCourseMapping) {
    Object.keys(userCourseMapping).forEach(courseListTypeName => {
      if (userCourseMapping[courseListTypeName].length > 0) {
        this.coursesLists.all[courseListTypeName].courses = userCourseMapping[courseListTypeName].map(course => {
          return Object.assign(course.pgCourseDetails, course);
        }) as Course[];
      }
    });
  }

  /**
   * Set active tab content
   *
   * @public
   * @param {*} tab
   * @memberof EmployeeDashboardHomeCTComponent
   */
  public setActive(tab: any): void {
    this.selectedTab = tab;
  }

  /**
   * Update course status and proper list counter
   *
   * @public
   * @param {*} courseDetails
   * @memberof EmployeeDashboardHomeCTComponent
   */
  updateCourseEvent(courseDetails: any) {
    const course: Course = courseDetails.course;
    switch (courseDetails.courseStatus) {
      case CourseStatus.Assessment:
        this.employeeNavBarService.setCourse(course);
        this.localStorageService.set('assessmentCourseId', course.courseDetailsId);
        this.router.navigate(['/employee/dashboard/assessment/' + courseDetails.assessmentPage]);
        break;
      case CourseStatus.InProgress:
        const newStatus = course.assessment ? CourseStatus.Assessment : CourseStatus.Completed;
        this.courseCounters.statusCount[CourseStatus.InProgress]--;
        this.courseCounters.statusCount[newStatus]++;
        if (newStatus === CourseStatus.Assessment && course.pgCourseDetails.assessment) {
          this.assessmentService.getEmployeeCourseAssessment(this.currentUser.userInfoMstrId, course.courseDetailsId)
          .subscribe(
            (assessment: EmployeeCourseAssessmentResponse) => {
            course.assessmentDetails = assessment;
            this.updateCourse(course, courseDetails.courseStatus, newStatus);
            this.assessmentService.updateCourseStatus(this.currentUser.userInfoMstrId, course.courseDetailsId, CANDIDATE_STATUS_NAMES.COURSE_COMPLETED).subscribe(response =>{ });
            }, (error) => {
              this.toastr.error('There isn\'t an assessment for this course.');
            }
          );
        } else {
          this.updateCourse(course, courseDetails.courseStatus, newStatus);
        }
        break;
      case CourseStatus.Overdue:
        const newOverdueStatus = course.assessment ? CourseStatus.Assessment : CourseStatus.Completed;
        this.courseCounters.statusCount[CourseStatus.Overdue]--;
        this.courseCounters.statusCount[newOverdueStatus]++;
        if (newOverdueStatus === CourseStatus.Assessment && course.pgCourseDetails.assessment) {
          this.assessmentService.getEmployeeCourseAssessment(this.currentUser.userInfoMstrId, course.courseDetailsId)
          .subscribe(
            (assessment: EmployeeCourseAssessmentResponse) => {
            course.assessmentDetails = assessment;
            this.updateCourse(course, courseDetails.courseStatus, newOverdueStatus);
            this.assessmentService.updateCourseStatus(this.currentUser.userInfoMstrId, course.courseDetailsId, CANDIDATE_STATUS_NAMES.COURSE_COMPLETED).subscribe(response =>{ });
            }, (error) => {
              this.toastr.error('There isn\'t an assessment for this course.');
            }
          );
        } else {
          this.updateCourse(course, courseDetails.courseStatus, newOverdueStatus);
        }
        break;
      default:
        const statusCounterName = course.recommended ? 'Recommended' : 'Wishlist';
        this.courseCounters.statusCount[statusCounterName]--;
        this.courseCounters.statusCount[CourseStatus.InProgress]++;
        this.updateCourse(course, courseDetails.courseStatus, CourseStatus.InProgress);
        this.assessmentService.updateCourseStatus(this.currentUser.userInfoMstrId, course.courseDetailsId, CANDIDATE_STATUS_NAMES.COURSE_STARTED).subscribe(response =>{ });
    }
  }

  /*
  * Goto Mini Assessment function
  *
  * */

  gotoMiniAssessment(evnt){

    console.log(evnt)
    console.log(evnt.empAssessmentMappingId)
    this.router.navigate(['/employee/dashboard/miniAssessment/' + evnt.empAssessmentMappingId]);


  }



  /**
   * Calls an API to update course status and updates course lists
   *
   * @public
   * @param {Course} course
   * @param {CourseStatus} status
   * @param {CourseStatus} newStatus
   * @memberof EmployeeDashboardHomeCTComponent
   */
  updateCourse(course: Course, status: CourseStatus, newStatus: CourseStatus) {
    const courseToUpdate: CourseUpdatePayload = {
      userId: course.userInfoMstrId,
      courseId: course.courseDetailsId,
      status: newStatus
    };
    this.coursesHttpService.updateUserCourses([courseToUpdate]).subscribe((data) => {
      const tabsToUpdate = course.recommended ? [CourseListFilter.all, CourseListFilter.mandatory] : [CourseListFilter.all, CourseListFilter.personal];
      tabsToUpdate.forEach(tab => {
        const courseList = this.coursesLists[tab];
        courseList[status].courses.splice(courseList[status].courses.indexOf(course), 1);
        courseList[newStatus].courses.push(course);
      });
    }, (error) => {
      // :TODO Waiting for a fixed backend issue to display the proper error if it is received.
      let msg = 'Something went wrong, please try again.';
      if (error && error.errorBean && error.errorBean.message) {
        msg += ' ' + error.errorBean.message;
      }
      this.toastr.error(msg);
    });
  }

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