import { AssessmentHttpService } from 'app/services/assessment/assessment-http.service';
import { OnChanges } from '@angular/core/src/metadata/lifecycle_hooks';
import { Component, OnInit, Input } from '@angular/core';
import { InfoDetails } from 'app/models/candidate-dashboard-response/info-details';
import { EventDetail } from 'app/models/candidate-dashboard-response/event-detail';
import { CandidateDashboardResponse } from 'app/models/candidate-dashboard-response/candidate-dashboard-response';
import { EmailService } from 'app/services/email.service';
import { Email } from 'app/models/email';
import { AuthService } from 'app/services/auth.service';
import { DomSanitizer, SafeResourceUrl, } from '@angular/platform-browser';
import { MAP_CANDIDATE_STATUS, CANDIDATE_STATUS, CANDIDATE_STATUS_NAMES } from 'app/models/candidateStatus';
import { LocalStorageService } from 'angular-2-local-storage';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { RoleNames } from 'app/models/auth/auth.model';
import { PrimarySkills, EventStatus, AssessmentDetails } from 'app/models/assessment/assessment.model';
import { Course } from 'app/models/capability-transformation/course-list.model';

@Component({
  selector: 'app-candidate-primary-skills',
  templateUrl: './candidate-primary-skills.component.html',
  styleUrls: ['./candidate-primary-skills.component.css'],
  providers: [
    EmailService, AuthService
  ]
})
export class CandidatePrimarySkillsComponent implements OnInit, OnChanges {
  @Input() primarySkills: PrimarySkills | null;
  @Input() assessmentDetails: AssessmentDetails | null;
  @Input() course: Course;
  @Input() isAssessment: any;

  _role: any;
  _isUserType: any;
  _eventDetails: EventDetail;
  _infoDetails: InfoDetails;
  // emailHistory: Email[];
  emailRecord: Email;
  Email: string;
  report: SafeResourceUrl;
  showReport = false;

  empData: any;

  access: any;
  enableRescheduleButtons = false;
  rescheduleSelection = '';
  mettleTestCompleted = true;

  get role() {
    return this._role;
  }
  get isUserType() {
    return this._isUserType;
  }

  @Input()
  set role(role) {
    this._role = role;
    this.setAccess();
  }
  @Input()
  set isUserType(isUserType) {
    this._isUserType = isUserType;

  }


  // At the moment The only field used by eventDetails was score and it was added to PrimarySkillsTimeline interface.
  /*
  get eventDetails() {
    return this._eventDetails;
  }

  @Input()
  set eventDetails(eventDetails) {
    this._eventDetails = eventDetails;
    this.setAccess();
  }
  */

  constructor(
    private emailService: EmailService,
    private authService: AuthService,
    private assessmentService: AssessmentHttpService,
    private sanitizer: DomSanitizer,
    private localStorageService: LocalStorageService,
    private toastr: ToastsManager

  ) { }

  ngOnInit() {
    this.setAccess();
    this.empData = this.localStorageService.get('userInfo');
    this.mettleTestCompleted = this.role !== RoleNames.Employee || this.role === RoleNames.Employee && this.primarySkills.primarySkillsDetails.PrimarySkillEvaluationStatus === EventStatus.COMPLETED || this.primarySkills.primarySkillsDetails.PrimarySkillEvaluationStatus  === EventStatus.Completed   ;

    if (this.mettleTestCompleted) {
      if (this.isAssessment === 'assessment'){
        if (this.role === RoleNames.Employee) {
          this.getAssessmentReport();
        } else {
          this.getAssessmentReport();
        }
      } else {
        if (this.role === RoleNames.Employee) {
          this.getReport(this.course);
        } else if (this.isUserType === RoleNames.Employee) {
          this.getReport(this.course);
        } else {
          this.getCandidateReport();
        }
      }
    }

    this.emailService.getUserEmailsStatus(this.primarySkills.user.emailId).subscribe(emailHistory => {
      // find the right email to know if it was sen't
      this.emailRecord = emailHistory.find(item => {
        return item.CASE_ID === 3;
      });
    });
    if (!this.course) {
      this.course = new Course();
    }
  }

  ngOnChanges() {
    this.ngOnInit();
  }

  getAssessmentReport() {
    console.log(this.primarySkills.user.emailId, this.assessmentDetails.employeeAssessmentMappingId);
    this.authService.getEmployeeMiniAssessmentPrimaryEvaluationReport( this.primarySkills.user.emailId, this.assessmentDetails.employeeAssessmentMappingId).then(responseData => {
      this.report = this.sanitizer.bypassSecurityTrustResourceUrl(responseData.candidate.testStatus.pdfReport);
      this.mettleTestCompleted = true;
      this.primarySkills.primarySkillsDetails.PrimarySkillEvaluationStatus = EventStatus.COMPLETED;
    }).catch(err => {
      console.log(err);
    });
  }

  getReport(course) {
    console.log(this.primarySkills.user.emailId, this.course.courseDetailsId);
    console.log(course, 'courseeeeeeeeeeeeeeeeeeee');
    this.authService.getEmployeePrimaryEvaluationReport( this.primarySkills.user.emailId, this.course.courseDetailsId).then(responseData => {
      this.report = this.sanitizer.bypassSecurityTrustResourceUrl(responseData.candidate.testStatus.pdfReport);
      this.mettleTestCompleted = true;
      /*this.assessmentService.updateCourseStatus(this.primarySkills.user.userInfoMstrId, this.course.courseDetailsId, CANDIDATE_STATUS_NAMES.METTL_APPROVED).subscribe(response => {
        this.primarySkills.user.mettlStatus = CANDIDATE_STATUS_NAMES.METTL_APPROVED;
      });*/
      this.primarySkills.primarySkillsDetails.PrimarySkillEvaluationStatus = EventStatus.COMPLETED;
    }).catch(err => {
      console.log(err);
    });
  }

  getCandidateReport() {
    this.authService.getCandidatePrimaryEvaluationReport({email: this.primarySkills.user.emailId}).then(responseData => {
      this.report = this.sanitizer.bypassSecurityTrustResourceUrl(responseData.candidate.testStatus.pdfReport);
      this.mettleTestCompleted = true;
      this.assessmentService.updateCourseStatus(this.primarySkills.user.userInfoMstrId, this.course.courseDetailsId, CANDIDATE_STATUS_NAMES.METTL_APPROVED).subscribe(response => {
        this.primarySkills.user.mettlStatus = CANDIDATE_STATUS_NAMES.METTL_APPROVED;
      });
      this.primarySkills.primarySkillsDetails.PrimarySkillEvaluationStatus = EventStatus.COMPLETED;
    }).catch(err => {
      console.log(err);
    });
  }



  get status(): number {
    return MAP_CANDIDATE_STATUS[this.primarySkills.user.mettlStatus];
  }


  // TODO: set values to show hide parts of the view depending on the candidate and role of the user
  private setAccess() {
    this.access = {
      rescheduleInterface: this.showRescheduleScreen(),
      taTimeline: this.showTaTimeline(),
      showtimeline: this.showTimeline(),
      showRescheduleButtons: this.showRescheduleInterface(),
      hasCoach: this.showCoachPofile(),
      testInProgress: this.testInProgress(),
      scheduleTest: this.scheduleTest(),
      primaryTestCompleted: this.showReport
    };

    // hide everything when showing the report
    if (this.showReport) {
      this.access.rescheduleInterface = false;
      this.access.taTimeline = false;
      this.access.showtimeline = false;
      this.access.showRescheduleButtons = false;
      this.access.hasCoach = false;
      this.access.testInProgress = false;
      this.access.scheduleTest = false;
    }
  }

  private reschedule() {
    return this.authService.candidateReschedule(this.primarySkills.user.userInfoMstrId);
  }

  private pgmIntervention() {
    return this.authService.candidateStatusUpdate({
      candidateStatus: CANDIDATE_STATUS_NAMES.TA_APPROVED, // CANDIDATE_STATUS.TA_APPROVED,
      fromId: this.empData.userInfoMstrId,
      toId: this.primarySkills.user.userInfoMstrId
    });
  }

  showReportDetails() {
    this.showReport = true;
    this.setAccess();
  }

  hideShowDetails() {
    this.showReport = false;
    this.setAccess();
  }

  enableReschedule(enable?: boolean) {
    this.enableRescheduleButtons = true;
    this.setAccess();
  }

  handleReschedule() {
    let promise;

    switch (this.rescheduleSelection) {
      case 'PGM_INTERVENTION':
        promise = this.pgmIntervention();
        break;
      case 'AUTO_SCHEDULE':
        promise = this.reschedule();
        break;
      default:
        console.error('there is no reschedule selection');
        break;
    }

    if (promise) {
      console.log('something happend');
      promise.then(resp => {
        // TODO make sure we reload candidateDashboard endpoint
        console.log('success reloading');
        window.location.reload();
      }).catch(e => {
        console.error(e);
      });
    }
  }

  private showRescheduleScreen() {
    return (this.status === CANDIDATE_STATUS.METTL_SCHEDULED && this.primarySkills.primarySkillsDetails.scheduleExpiryDate < Date.now());
  }

  private showTaTimeline() {
    return this.status >= CANDIDATE_STATUS.METTL_SCHEDULED;
  }

  private showCoachPofile() {
    return this.primarySkills.coach !== null && this.role !== 'Coach';
  }

  private testInProgress() {
    // TODO: what status should we use to determine if the test its in progress?
    // return this.primarySkills.user.mettlStatus === CandidatePrimarySkillsComponent.TEST_IN_PROGRESS;
  }

  private showRescheduleInterface() {
    return this.showRescheduleScreen() && this.enableRescheduleButtons;
  }

  private scheduleTest() {
    return this.status === CANDIDATE_STATUS.METTL_COACH_ASSIGNED;
  }

  private testCompleted() {
    if ((this.status > CANDIDATE_STATUS.METTL_SCHEDULED && this.status < CANDIDATE_STATUS.METTL_REJECTED)
      || (this.status >= CANDIDATE_STATUS.METTL_REJECTED && this.status < CANDIDATE_STATUS.METTL_COACH_ASSIGNED)
      || (this.status > CANDIDATE_STATUS.METTL_COACH_ASSIGNED)) {
      return true;
    } else {
      return false;
    }
  }

  private showTimeline() {
    // reschedule avilable do not show this
    if (this.showRescheduleScreen() || this.testInProgress()) {
      return false;
    } else {
      return true;
    }
  }

  /* Employee methods */
  employeeLaunchMettlTest(assessment: {isAssessment: string, assessmentId: any}) {
    console.log(this.primarySkills.primarySkillsDetails.testLink)
    if (this.primarySkills.primarySkillsDetails.testLink) {
      if(assessment.isAssessment === 'assessment') {
        this.assessmentService.updateAssessmentStatus(this.primarySkills.user.userInfoMstrId, assessment.assessmentId, CANDIDATE_STATUS_NAMES.METTL_STARTED).subscribe(response => {
          this.primarySkills.user.mettlStatus = CANDIDATE_STATUS_NAMES.METTL_STARTED;
        });
      }else {
        this.assessmentService.updateCourseStatus(this.primarySkills.user.userInfoMstrId, this.course.courseDetailsId, CANDIDATE_STATUS_NAMES.METTL_STARTED).subscribe(response => {
          this.primarySkills.user.mettlStatus = CANDIDATE_STATUS_NAMES.METTL_STARTED;
        });
      }
      window.open(this.primarySkills.primarySkillsDetails.testLink);
    } else {
      this.toastr.error('There isn\'t a link for the test, please contact the system administrator to solve that.');
    }
  }
    employeeCompleteMettlTest(assessment: {isAssessment: string, assessmentId: any}) {
      if (assessment.isAssessment === 'assessment') {
        this.assessmentService.updateAssessmentStatus(this.primarySkills.user.userInfoMstrId, assessment.assessmentId, CANDIDATE_STATUS_NAMES.METTL_COMPLETED).subscribe(response => {
          this.primarySkills.user.mettlStatus = CANDIDATE_STATUS_NAMES.METTL_COMPLETED;
          this.getAssessmentReport();
        });
      }else {
        this.assessmentService.updateCourseStatus(this.primarySkills.user.userInfoMstrId, this.course.courseDetailsId, CANDIDATE_STATUS_NAMES.METTL_APPROVED).subscribe(response => {
          this.primarySkills.user.mettlStatus = CANDIDATE_STATUS_NAMES.METTL_APPROVED;
          this.getReport(this.course);
        });
      }
  }

}
