import { Component, OnInit, OnChanges, Output, EventEmitter } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { EmployeeWizardService } from './employee-wizard.service';
import { EmployeeHttpService } from './../../services/employee/employee-http.service';
import { LocalStorageService } from 'angular-2-local-storage';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { AssessmentHttpService } from 'app/services/assessment/assessment-http.service';
import { EmployeeCourseAssessmentPayload } from 'app/models/assessment/employee-assessment.model';
import { Course } from 'app/models/capability-transformation/course-list.model';
import { EmployeeFirstTimeActionsButtonsService, Action, Result } from './employee-first-time-actions-buttons.service';
import { environment } from '../../../environments/environment.dev';

const img_path_prefix = environment.imageUrl+'/assets/img/employee/wizard/';
const img_path_suffix = '.png';

const capability = {
  img: img_path_prefix + 'ct' + img_path_suffix,
  h1: '<h1>CAPABILITY</h1><h1>TRANSFORMATION</h1>'
};

const rootUrl = '/employee/first-time-wizard/';

const wizardPages = [
  {
    name: 'capability_1',
    img: capability.img,
    h1: capability.h1,
    background: 'linear-gradient(315deg, #37EA92 0%, #0FBDBB 100%);',
    navigation: {
      skip: '',
      back: '/employee/profile',
      next: rootUrl + 'capability_2'
    }
  },
  {
    name: 'capability_2',
    img: capability.img,
    h1: capability.h1,
    background: 'linear-gradient(315deg, #37EA92 0%, #0FBDBB 100%);',
    navigation: {
      skip: '',
      back: rootUrl + 'capability_1',
      next: rootUrl + 'platform'
    }
  },
  {
    name: 'platform',
    img: img_path_prefix + 'platform' + img_path_suffix,
    h1: '<h1>PLATFORM</h1>',
    background: 'linear-gradient(315deg, #37EA92 0%, #0FBDBB 100%);',
    navigation: {
      skip: '',
      back: rootUrl + 'capability_2',
      next: rootUrl + 'innovation'
    }
  },
  {
    name: 'innovation',
    img: img_path_prefix + 'innovation' + img_path_suffix,
    h1: '<h1>INNOVATION</h1>',
    background: 'linear-gradient(315deg, #37EA92 0%, #0FBDBB 100%);',
    navigation: {
      skip: '/employee/dashboard',
      back: rootUrl + 'platform',
      next: '/employee/dashboard'
    }
  }
];

@Component({
  selector: 'app-employee-first-time-wizard',
  templateUrl: './employee-first-time-wizard.component.html',
  styleUrls: ['./employee-first-time-wizard.component.css'],
  providers: [EmployeeWizardService]
})
export class EmployeeFirstTimeWizardComponent implements OnInit {
  img = capability.img;

  currentPageNumber: number;

  currentPageData: {
    name: string,
    img: string,
    h1: string,
    background: string,
    navigation: {
      skip: string,
      back: string,
      next: string
    }
  };

  employee: any = {};

  displayDoneButton = false;
  @Output() submitAction = new EventEmitter();
  constructor(
    protected localStorageService: LocalStorageService,
    private router: Router, private employeeWizardService: EmployeeWizardService,
    private dataService: EmployeeHttpService,
    private assessmentHttpService: AssessmentHttpService,
    private toast: ToastsManager,
    private route: ActivatedRoute,
    private actionsButtons: EmployeeFirstTimeActionsButtonsService
  ) {
    this.employee = this.localStorageService.get('userInfo');
    this.employeeWizardService.currentPage.subscribe((value: number) => {
      this.currentPageNumber = value;
      this.currentPageData = wizardPages[this.currentPageNumber];
      this.displayDoneButton = this.currentPageNumber === 3 || (!this.employee.firstTimeLogin && this.currentPageNumber > 0);
    });
  }

  ngOnInit() {

  }

  previous() {
    let url: string;
    if (!this.employee.firstTimeLogin && this.currentPageNumber !== 1) {
      url = '/employee/dashboard/old';
    } else {
      this.displayDoneButton = false;
      this.currentPageNumber -= 1;
      url = this.currentPageData.navigation.back;
    }
    this.router.navigate([url]);
  }

  next() {
    if (this.currentPageNumber === 1) {
      this.addUserCourses();
    } else {
      this.skip();
    }
  }

  skip() {
    if (!this.employee.firstTimeLogin && this.currentPageNumber !== 0) {
      // this.router.navigate(['/employee/dashboard']);
      this.submit();
    } else {
      this.displayDoneButton = true;
      this.currentPageNumber += 1;
      this.router.navigate(['/employee/dashboard/old']);
    }
  }

  addUserCourses() {
    this.employeeWizardService.courses.subscribe((courses: any[]) => {
      const wishlistCourses = courses.map(course => {
        return { userId: course.userId, courseId: course.courseId };
      });
      if (courses.length > 0) {
        this.dataService
          .addUserCourses(wishlistCourses).subscribe((data) => {
            const courseDetails: EmployeeCourseAssessmentPayload[] = courses.map(course => {
              return {
                assessment: course.assessment || false,
                courseId: course.courseId,
                userInfoMstrId: course.userId
              } as EmployeeCourseAssessmentPayload;
            });
            this.assessmentHttpService.create(courseDetails).subscribe((assessmentData) => {
              this.toast.success('The courses were successfully added.');
              this.skip();
            }, (error) => {
              this.toast.error('Something went wrong adding a new assessment record for the selected courses, please try to add the courses again.');
            });
          }, (error) => {
            this.toast.error('Something went wrong adding the courses, please try to add the courses again.');
          });
      } else {
        this.skip();
      }
    });
  }

  submit() {
    const execute = () => {
      this.dataService
        .updateFirstTimeLoginStatus(this.employee.userInfoMstrId)
        .subscribe(
          (data) => {
            this.employee.firstTimeLogin = false;
            this.localStorageService.set('userInfo', this.employee);
            this.router.navigate(['/employee/dashboard']);
          },
          (error) => {
            this.toast.error('Something went wrong, please try to submit again.');
          }
        );

    };
    if (this.actionsButtons.observersButtonsAction().length) {

      this.actionsButtons.actionChange(Action.submit);
      this.actionsButtons.resultAction$
        .subscribe(r => {
          if (r === Result.completed) {
            execute();
          }
        });
    }
    else {
      execute();
    }


  }
}
