import {Component, OnInit, Input, ElementRef, ViewChild} from '@angular/core';
import { AuthService } from '../../../services/auth.service';
import { LocalStorageService } from 'angular-2-local-storage';
import {Router, ActivatedRoute} from '@angular/router';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { NavBarService } from '../../../pgm/pgm.service';
import { EmployeeHttpService } from './../../../services/employee/employee-http.service';
import { environment } from '../../../../environments/environment.dev';

@Component({
  selector: 'app-course-and-assessment',
  templateUrl: './course-and-assessment.component.html',
  styleUrls: ['./course-and-assessment.component.scss']
})
export class CourseAndAssessmentComponent implements OnInit {
  img_path_prefix = environment.imageUrl+'/assets/img/employee/wizard/';
  img_path_suffix = '_icon.png';
  public currentPageNumber = 0;
  currentPageData: { title: string, back: string };
  onlyOneRole: boolean;
  pages = [
    {
      name: 'capability',
      img: this.img_path_prefix + 'CT_bg.png',
      h1: 'Capability Transformation',
      pArray: [
        'User can enhance and develop their skillsets by taking online courses or by using the Playground – Sandbox.'
        + 'Use the Capability Transformation as a',
        '<strong>Learning Portal</strong> - Path to Excellence & Proficiency level courses.'
        + 'Excellent option leading your way to gain a certified course through mentor assistance and assessment.',
        '<strong>Learning Portal + Sandbox</strong> - '
        + 'Help the Employee to practice themselves in the new skill set in the available sandbox.',
        '<strong>Pre-defined Transformation Plan</strong> - '
        + 'create a Learning plan with a set of initial assessment, recommended courses, use cases and exit assessment.'
      ],
      footer: {
        rectangle: 'left',
        circle1: 'right',
        circle2: 'right'
      }
    },
    {
      name: 'platform',
      img: this.img_path_prefix + 'Platform_bg.png',
      h1: 'Platform',
      h1Line: '',
      pArray: [
        'Reusable Components are available and listed with usage details and contributed by the Employee from /to Platforms.'
        + 'Component Repository portal list\'s the components ranging from both Front End and Back End.',
        'These components can be easily plugged into the use case developed by the Altimetrian which helps to accelerate the development.'
      ],
      footer: {
        rectangle: 'left',
        circle1: 'left',
        circle2: 'left'
      }
    },
    {
      name: 'innovation',
      img: this.img_path_prefix + 'Innovation_bg.png',
      h1: 'Innovation',
      pArray: [
        'Ideate inventive thoughts to offer better potential product or solutions. '
        + 'Turn your ideation in to intuitive Proof of Concept (PoC) there by demonstrating its practical potentiality.',
        'Propose sufficient evidence of the technical viability of your innovation there by providing the first version of the product.'
      ],
      footer: {
        rectangle: 'right',
        circle1: 'left',
        circle2: 'left'
      }
    }
  ];
  // mycolor: any;
  skillCategory: any;
  selectedCategoriesArr: any = [];
  showcatdispDiv: boolean = false;
  selectable: boolean = true;
  removable: boolean = true;
  searchedCResult: any;
  UID: any;
  searchedText: string;
  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any
  };
  initials = '';
  @ViewChild('mat-chip-list') chipList: ElementRef;
  employee: any = {};
  constructor(protected localStorageService: LocalStorageService,
              private AuthService: AuthService,
              private router: Router,
              private route: ActivatedRoute,
              private toastr: ToastsManager,
              private dataService: EmployeeHttpService,
              private navBarService: NavBarService
  ) {
    this.navBarService.setCurrentPage(3);

    this.route.params.subscribe( params =>
      this.UID = params['id']
    );
    console.log(this.UID, 'uid');
    this.getAllCategory();
    if (window.location.origin !== 'http://localhost:8080') {
      var empData;
      empData = this.localStorageService.get('userInfo');
      this.empData = empData;
      if (this.empData['roles'].length > 1) {
        this.onlyOneRole = false;
      } else {
        this.onlyOneRole = true;
      }
      console.log(this.empData, "userInfo Detailssssss")
      if (this.empData['fullName']) {
        this.initials = this.empData['fullName'].replace(/\W*(\w)\w*/g, '$1').toUpperCase();
      }
    } else {
      this.initials = 'LS';
    }
    this.employee = this.localStorageService.get('userInfo');
    this.localStorageService.remove('serachedText');
  }

  ngOnInit() {
  }
  showPreSelected(preSelected) {
    preSelected.forEach(element => {
      this.skillCategory.forEach(list => {
        if (element.skillTrackMstrId === list.skillTrackMstrId) {
          list.isSelected = true;
        }
      });
    });
    this.selectedCategoriesArr = preSelected;
  }
  previous() {
  }
  next() {
  }

  getAllCategory() {
    this.AuthService.getAllSkillTrackMstr().then(resp => {
      resp.pgSkillTrackMstr.forEach(element => {
        element['isSelected'] = false;
      });
      this.skillCategory = resp.pgSkillTrackMstr;
      if (this.localStorageService.get('selectedCourse')) {
        this.showPreSelected(this.localStorageService.get('selectedCourse'))
      }
    });
  }

  addSelectedCategory(e) {
    if (this.selectedCategoriesArr.indexOf(e) !== -1) {
      console.log("Item already exists");
    }
    else {
      this.selectedCategoriesArr.push(e);
    }
  }

  displaySelectedCats() {
    if (this.showcatdispDiv == false) {
      this.showcatdispDiv = true;
    }
    else if (this.showcatdispDiv == true) {
      this.showcatdispDiv = false;
    }
  }

  removeCatsSelected(cats, index) {
    //et txt = this.skillCategory.indexOf(cats);
    let txt = this.skillCategory.findIndex((obj => obj.skillTrackMstrId == cats.skillTrackMstrId));
    this.skillCategory[txt].isSelected = false;
    this.selectedCategoriesArr.splice(index, 1);
    if (this.selectedCategoriesArr.length === 0) {
      this.showcatdispDiv = false;
    }
  }

  execute() {
    this.dataService
      .updateFirstTimeLoginStatus(this.employee.userInfoMstrId)
      .subscribe(
        (data) => {
          this.employee.firstTimeLogin = false;
          this.localStorageService.set('userInfo', this.employee);
          // this.router.navigate(['employeedashboard']);
          console.log(this.employee.firstTimeLogin, '----- FistimeLoginStatus ----');
        },
        (error) => {
          this.toastr.error('Something went wrong, please try to submit again.');
          this.router.navigate(['employee/first-time']);
        }
      );
  };

  SearchforCourses(values) {
    this.searchedText = values.target.value;
    if (values.keyCode === 13 && values.target.value.length > 2) {
      this.setSearchedTextToLocal();
    }

  }

  setSearchedTextToLocal() {
    if (this.searchedText !== undefined) {
      this.localStorageService.remove('serachedText');
      this.localStorageService.remove('selectedCourse');
      this.localStorageService.set('serachedText', this.searchedText);
     // this.router.navigate(['employee/employeeCourseSelection']);
      // this.AuthService.getCourseNuseCases(values).then(resp =>{
      //   if((resp.status == 200 && resp.error == null) || (resp.error == null)){
      //     this.searchedCResult = resp;
      //   this.router.navigate(['employee/bnyEmployeeCourseSelection'], this.searchedCResult);
      //   this.execute();
      //   }
      // });

      if (this.UID === 1 || this.UID === "1") {
        this.router.navigate(['talent-transformation/employee/SelectCourseAndAssessment']);
      }
      else {
        this.router.navigate(['talent-transformation/employee/SelectLearningPath']);
      }
    }
  }

  goToNextPage() {
    if (this.selectedCategoriesArr.length != -1) {
      // this.employeeService.setSelectedCourse(this.selectedCategoriesArr);
      if (this.localStorageService.get('selectedCourse')) {
        this.localStorageService.remove('selectedCourse');
        this.localStorageService.set('selectedCourse', this.selectedCategoriesArr);
      } else {
        this.localStorageService.set('selectedCourse', this.selectedCategoriesArr)
      }
      if (this.UID === 1 || this.UID === "1") {
        this.router.navigate(['talent-transformation/employee/SelectCourseAndAssessment']);
      }
      else {
        this.router.navigate(['talent-transformation/employee/SelectLearningPath']);
      }
     // this.execute();
    }
  }

  skipFirstPage() {
    this.router.navigate(['talent-transformation/landing/employee']);
    this.execute();
  }
}
