import { AssessmentHttpService } from 'app/services/assessment/assessment-http.service';
import { PgSkillTrackDtlsList } from 'app/models/skills.model';
import { Component, OnInit, Input, OnDestroy, OnChanges } from '@angular/core';
import { AuthService } from 'app/services/auth.service';
import { UserInfo } from 'app/models/userInfo.model';
import { LocalStorageService } from 'angular-2-local-storage/dist';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { ResponseSetupWorkSpace, SetupWorkspacePayload, SandboxSetupProcessWorkSpace, state } from 'app/models/sandbox-progress.model';
import { CANDIDATE_STATUS_NAMES } from 'app/models/candidateStatus';
import { ProgressStateSetupWorkspaceService } from 'app/employee/employee-dashboard/employee-sandbox/progress-state-setup-workspace.service';
import { User, TechnicalUsecase, UseCaseNames, UseCases, AssessmentDetails } from 'app/models/assessment/assessment.model';
// import {AssessmentDetails} from "app/models/assessment/assessment.model";
import { environment } from '../../../../../environments/environment.dev';
enum SandboxStatus {
  Created = 'Created',
  Started = 'Started',
  Terminated = 'Terminated'
}
@Component({
  selector: 'app-employee-assessment-technical',
  templateUrl: './employee-assessment-technical.component.html',
  styleUrls: ['./employee-assessment-technical.component.scss']
})
export class EmployeeAssessmentTechnicalComponent implements OnInit, OnChanges, OnDestroy {
  @Input() technicalUsecase: TechnicalUsecase | null;
  @Input() useCaseName: UseCaseNames | null;
  @Input() role: any;
  @Input() isUserType: any;
  @Input() assessmentDetails: AssessmentDetails | null;
  @Input() isAssessment: any;

  skillTrackDtls: PgSkillTrackDtlsList;

  public sandboxStatusEnum = SandboxStatus;
  public sandboxStatus: SandboxStatus;
  workspace: ResponseSetupWorkSpace;
  remainingTime = 0;
  sandboxSetupProcessTimeout: any;
  sandboxAbortNeeded = false;
  useCaseDescription: string;
  useCase = UseCases.Technical;
  imageUrl: string = environment.imageUrl;
  constructor(
    private authService: AuthService,
    private assessmentService: AssessmentHttpService,
    private localStorageService: LocalStorageService,
    private sandboxStateService: ProgressStateSetupWorkspaceService,
    private toastr: ToastsManager
  ) { }

  ngOnInit() {
    if (this.useCaseName) {
      this.useCase = UseCases[this.useCaseName];
    }
    if (this.technicalUsecase.sandboxDir) {
      this.sandboxStateService.setupProcessWorked.subscribe((sandboxState: SandboxSetupProcessWorkSpace) => {
        const sandboxCreated = sandboxState && sandboxState.state !== state.NONE;
        this.sandboxAbortNeeded = sandboxCreated && sandboxState.data.bundleId !== this.technicalUsecase.sandboxDir.sbundleId;
        if (sandboxCreated && !this.sandboxAbortNeeded) {
          this.workspace = sandboxState.data;
          this.createSetupWorkspaceTimeout(sandboxState.data.createdTime);
        }
      });
    }
    if (this.isAssessment === 'assessment') {
      this.assessmentService.getMiniAssessmentUsecase(this.technicalUsecase.user.userInfoMstrId, this.useCase.id, this.technicalUsecase.courseId).subscribe(usecaseData => {
        this.useCaseDescription = usecaseData.usecaseDescription;
      });
    } else {
      this.assessmentService.getUsecase(this.technicalUsecase.user.userInfoMstrId, this.useCase.id, this.technicalUsecase.courseId).subscribe(usecaseData => {
        this.useCaseDescription = usecaseData.usecaseDescription;
      });
    }
  }

  ngOnChanges() {
   this.ngOnInit();
  }

  setupWorkspace() {
    if (this.technicalUsecase.sandboxDir) {
      if (this.sandboxAbortNeeded) {
        this.toastr.error('You have already created a sandbox for a different environment. You have to delete it in order to be able to setup a new workspace for this usecase.');
      }else {
        this.authService.setupWorkSpace(this.technicalUsecase.sandboxDir).then( (workspace: ResponseSetupWorkSpace) => {
          this.workspace = workspace;
          if (!workspace.registrationCode) {
            this.sandboxStatus = null;
            this.toastr.error('There was an error creating the workspace. Please try again.');
          }else {
            this.sandboxStatus = SandboxStatus.Started;
            this.sandboxStateService.setupProcessWorked.next({ show: true, state: state.Completed, data: workspace });
            this.createSetupWorkspaceTimeout(workspace.createdTime);
          }
        }).catch(error => {
          this.toastr.error('There was an error creating the workspace: ', error);
        });
      }
    }else {
      this.toastr.error('There isn\'t any directory available to create a new sandbox.');
    }
  }

  createSetupWorkspaceTimeout(createdTime: number) {
    const remainingTime = 30 - this.sandboxStateService.calculateTimeFromCreated(createdTime);
    if (remainingTime > 0) {
      this.sandboxStatus = SandboxStatus.Started;
      this.sandboxSetupProcessTimeout = setTimeout(() => {
        this.sandboxStatus = SandboxStatus.Created;
      }, remainingTime * 1000 * 60);
    }else {
      this.sandboxStatus = SandboxStatus.Created;
    }
  }

  launchEnvironment() {
    window.open(this.workspace.awsClientAccessUrl);
  }

  submit() {

    if (this.isAssessment === 'assessment') {
      // It is necessary to send an initial status before send the completion status change.
      const aditionalStatus: CANDIDATE_STATUS_NAMES = this.useCase.name === UseCaseNames.Technical ? CANDIDATE_STATUS_NAMES.MINI_PG_STARTED : CANDIDATE_STATUS_NAMES.MAIN_PG_STARTED;
      const status: CANDIDATE_STATUS_NAMES = this.useCase.name === UseCaseNames.Technical ? CANDIDATE_STATUS_NAMES.MINI_PG_COMPLETED : CANDIDATE_STATUS_NAMES.MAIN_PG_COMPLETED;
      this.assessmentService.updateAssessmentStatus(this.technicalUsecase.user.userInfoMstrId, this.technicalUsecase.courseId, aditionalStatus).subscribe(response => {
        this.technicalUsecase.user.mettlStatus = aditionalStatus;
        this.assessmentService.updateAssessmentStatus(this.technicalUsecase.user.userInfoMstrId, this.technicalUsecase.courseId, status).subscribe(response2 => {
          this.technicalUsecase.user.mettlStatus = status;
          this.toastr.success('Successfully submitted');
        }, (error) => {
          this.toastr.error('There was an error, please try again.');
        });
      }, (error) => {
        this.toastr.error('There was an error, please try again.');
      });
    } else {
      // It is necessary to send an initial status before send the completion status change.
      const aditionalStatus: CANDIDATE_STATUS_NAMES = this.useCase.name === UseCaseNames.Technical ? CANDIDATE_STATUS_NAMES.MINI_PG_STARTED : CANDIDATE_STATUS_NAMES.MAIN_PG_STARTED;
      const status: CANDIDATE_STATUS_NAMES = this.useCase.name === UseCaseNames.Technical ? CANDIDATE_STATUS_NAMES.MINI_PG_COMPLETED : CANDIDATE_STATUS_NAMES.MAIN_PG_COMPLETED;
      this.assessmentService.updateCourseStatus(this.technicalUsecase.user.userInfoMstrId, this.technicalUsecase.courseId, aditionalStatus).subscribe(response => {
        this.technicalUsecase.user.mettlStatus = aditionalStatus;
        this.assessmentService.updateCourseStatus(this.technicalUsecase.user.userInfoMstrId, this.technicalUsecase.courseId, status).subscribe(response2 => {
          this.technicalUsecase.user.mettlStatus = status;
          this.toastr.success('Successfully submitted');
        }, (error) => {
          this.toastr.error('There was an error, please try again.');
        });
      }, (error) => {
        this.toastr.error('There was an error, please try again.');
      });
    }
  }

  ngOnDestroy() {
    clearInterval(this.sandboxSetupProcessTimeout);
  }

}
