import { Component, OnInit, Inject } from '@angular/core';
import { UserInfo } from '../../models/userInfo.model';
import { AuthService } from '../../services/auth.service';
import { LocalStorageService } from 'angular-2-local-storage';
import { EmployeeNavBarService } from '../employee-dashboard/employee-nav-bar.service';
import { EmployeeHttpService } from 'app/services/employee/employee-http.service';
// import { CapitalizeFirstLeterPipe } from '../../custom-pipes/first-leter-caps';
import { EmployeeService } from '../../employee.service';
import { Subject } from 'rxjs/Rx';
import { DOCUMENT } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { ToastsManager } from 'ng2-toastr';
import _ from 'lodash';
import { environment } from '../../../environments/environment.dev';
const dashboardPages = [
  { title: 'Welcome to Playground', back: '' },
  { title: 'bny-dashboard', back: 'back' },
];


@Component({
  selector: 'app-bny-employee-course-selection',
  templateUrl: './bny-employee-course-selection.component.html',
  styleUrls: ['./bny-employee-course-selection.component.scss'],
  providers: [EmployeeNavBarService]
})
export class BnyEmployeeCourseSelectionComponent implements OnInit {

  documentDetails;
  selectedTab: number;
  showcatdispDiv: boolean = false;
  roleStatus: boolean = false;
  showArow: boolean;
  showCourseSelection: boolean;
  coursesLists;
  learningPath;
  learningPathCardDetails;
  allCourses;
  primaryAssessment;
  technicalAssessment;
  businessAssessment;
  allReservedCourses;
  primaryReservedAssessment;
  technicalReservedAssessment;
  businessReservedAssessment;
  allSelectedCourses: any = [];
  primarySelectedAssessment: any = [];
  technicalSelectedAssessment: any = [];
  learningSeletedPath: any = [];
  businessSelectedAssessment: any = [];
  skillMstrIds;
  selectedCoursesDetails: any = [];
  selectedCourses: any = [];
  selectedCourseIdCollection: string;
  skills: any;
  selectedSkill: any = [];
  loader = true;
  currentPageData: { title: string, back: string };
  onlyOneRole: boolean;
  public currentPageNumber;
  img_path = environment.imageUrl+'/assets/img/Taflow/';
  initials = '';
  employee: any = {};
  tabDetails = [
    { className: 'first', Id: 2, containerText: 'Learning Path', count: 0 },
    { className: 'second', Id: 2, containerText: 'Courses', count: 0 },
    { className: 'third', Id: 3, containerText: 'Primary Assessment', count: 0 },
    { className: 'fourth', Id: 4, containerText: 'Technical Assessment', count: 0 },
    { className: 'fifth', Id: 1, containerText: 'Business Assessment', count: 0 },
  ];
  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any,
    email: any
  };
  frmCandD:boolean = false;
  imageUrl: string = environment.imageUrl;
  constructor( @Inject(DOCUMENT) document, protected localStorageService: LocalStorageService,
    private employeeNavBarService: EmployeeNavBarService,
    private employeeHttpService: EmployeeHttpService,
    private employeeService: EmployeeService,
    private route: ActivatedRoute,
    private AuthService: AuthService,
    private toaster: ToastsManager,
    private router: Router,
  ) {
    console.log(document);
    this.showCourseSelection = false;
    this.documentDetails = document;
    this.selectedTab = 0;
    this.getAllSkills();
    // this.route.queryParams.subscribe(params => {
    //   console.log(params)
    // });
    // this.employeeNavBarService.getSelectedCourse();
    // this.selectedSkill = this.employeeService.getSelectedCourse();
    console.log(this.selectedSkill);
    this.callGetSeachedData();
    if (window.location.origin !== 'http://localhost:8080') {
      let empData;
      empData = this.localStorageService.get('userInfo');
      this.empData = empData;
      if (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');
  }

  ngOnInit() {
    this.currentPageData = dashboardPages[0];
  }
  toggleActive(newValue: number) {
    this.selectedTab = newValue;
  }
  callGetSeachedData() {
    if (this.localStorageService.get('selectedCourse') && this.localStorageService.get('serachedText')) {
      const getIds = this.selectedSkilIdDetails(this.localStorageService.get('selectedCourse'));
      const searchedText = '&keyword=' + this.localStorageService.get('serachedText');
      const searchedTextAndId = getIds + searchedText;
      this.getBnyCourseDetails(searchedTextAndId);
    } else if (this.localStorageService.get('selectedCourse')) {
      const getIds = this.selectedSkilIdDetails(this.localStorageService.get('selectedCourse'));
      this.getBnyCourseDetails(getIds);
    } else if (this.localStorageService.get('serachedText')) {
      const searchedText = '?keyword=' + this.localStorageService.get('serachedText');
      this.getBnyCourseDetails(searchedText);
    }
  }
  smoothScroll(target) {
    // document.getElementById('el');
    let scrollContainer = target;
    do { // find scroll container
      scrollContainer = scrollContainer.parentNode;
      if (!scrollContainer) return;
      scrollContainer.scrollTop += 1;
    } while (scrollContainer.scrollTop === 0);

    let targetY = 0;
    do { // find the top of target relatively to the container
      if (target == scrollContainer) break;
      targetY += target.offsetTop;
    } while (target = target.offsetParent);

    var scroll = function (c, a, b, i) {
      i++; if (i > 30) return;
      c.scrollTop = a + (b - a) / 30 * i;
      setTimeout(function () { scroll(c, a, b, i); }, 20);
    }
    // start scrolling
    scroll(scrollContainer, scrollContainer.scrollTop, targetY, 20);
  }
  getBnyCourseDetails(selectedSkill) {
    this.loader = true;
    this.employeeHttpService.getBNYEmployeeCourseDetails(selectedSkill).subscribe(response => {
      console.log(response);
      this.coursesLists = response;
      this.allCourses = response.allCourses;
      this.learningPath = response.learningPath;
      this.businessAssessment = response.businessAssessment;
      this.technicalAssessment = response.technicalAssessment;
      this.primaryAssessment = response.primaryAssessment;
      this.allReservedCourses = response.allCourses;
      this.businessReservedAssessment = response.businessAssessment;
      this.technicalReservedAssessment = response.technicalAssessment;
      this.primaryReservedAssessment = response.primaryAssessment;
      this.skillMstrIds = response.skillMstrIds;
      if (this.localStorageService.get('serachedText')) {
        this.selectedSkill = _.filter(this.skills, (v) => _.includes(this.skillMstrIds, v.skillTrackMstrId));
      }

      this.getCourseCount(response);
      this.loader = false;
    }, (error) => {
      this.loader = false;
      this.allCourses = [];
      this.primaryAssessment = [];
      this.technicalAssessment = [];
      this.businessAssessment = [];
    });
  }
  getCourseCount(courseList) {
    this.tabDetails.forEach((data) => {
      if (data.containerText === 'Learning Path' && courseList.learningPath) {
        data.count = courseList.learningPath.length;
      } else if (data.containerText === 'Courses' && courseList.allCourses) {
        data.count = courseList.allCourses.length;
      } else if (data.containerText === 'Primary Assessment' && courseList.primaryAssessment) {
        data.count = courseList.primaryAssessment.length;
      } else if (data.containerText === 'Technical Assessment' && courseList.technicalAssessment) {
        data.count = courseList.technicalAssessment.length;
      } else if (data.containerText === 'Business Assessment' && courseList.businessAssessment) {
        data.count = courseList.businessAssessment.length;
      }
    })
  }

  selectCourse(course: any = {}, category) {
    if (course.selected) {
      course.selected = false;
      if (category === 'course') {
        this.allSelectedCourses = this.allSelectedCourses.filter(item => item.courseDetailsId !== course.courseDetailsId);
        // this.selectedCourses = this.selectedCourses.filter(item => item.courseDetailsId !== course.courseDetailsId);
      } else if (category === 'Primary') {
        this.primarySelectedAssessment = this.primarySelectedAssessment.filter(item => item.assessmentId !== course.assessmentId);
        // this.selectedCourses = this.selectedCourses.filter(item => item.assessmentId !== course.assessmentId);
      } else if (category === 'Technical') {
        this.technicalSelectedAssessment = this.technicalSelectedAssessment.filter(item => item.id !== course.id);
        // this.selectedCourses = this.selectedCourses.filter(item => item.id !== course.id);
      } else if (category === 'Business') {
        this.businessSelectedAssessment = this.businessSelectedAssessment.filter(item => item.id !== course.id);
        // this.selectedCourses = this.selectedCourses.filter(item => item.id !== course.id);
      } else if (category === 'Learning Path') {
        this.learningSeletedPath = this.learningSeletedPath.filter(item => item.id !== course.id);
      }
      this.selectedCourses = this.selectedCourses.filter(item => item.courseId !== course.courseDetailsId);
    } else {
      course.selected = true;
      // this.selectedCourses.push({ 'courseId': course.courseDetailsId, "assessment": course.assessment });
      // this.selectedCoursesDetails.push(course)
      if (category === 'course') {
        // this.selectedCourses.push({ 'courseId': course.courseDetailsId, "assessment": course.assessment });
        this.allSelectedCourses.push(course);
      } else if (category === 'Primary') {
        // this.selectedCourses.push({ 'courseId': course.courseDetailsId, "assessment": course.assessment });
        this.primarySelectedAssessment.push(course);
      } else if (category === 'Technical') {
        // this.selectedCourses.push({ 'courseId': course.courseDetailsId, "assessment": course.assessment });
        this.technicalSelectedAssessment.push(course);
      } else if (category === 'Business') {
        // this.selectedCourses.push({ 'courseId': course.courseDetailsId, "assessment": course.assessment });
        this.businessSelectedAssessment.push(course);
      } else if (category === 'Learning Path') {
        // this.selectedCourses.push({ 'courseId': course.courseDetailsId, "assessment": course.assessment });
        this.learningSeletedPath.push(course);
      }
      this.selectedCourses.push({ 'courseId': course.courseDetailsId, 'assessment': course.assessment });
    }
    console.log(this.selectedCourses, 'selectedCourses');
    console.log(this.selectedCoursesDetails, 'selectedCoursesDetails');
  }

  getAllSkills() {
    this.AuthService.getAllSkillTrackMstr().then(resp => {
      console.log(resp, 'getAllSkills');
      this.skills = resp.pgSkillTrackMstr;
    }).catch(err => {
      console.log(err);
    })
  }

  selectedSkilIdDetails(selectedskillId) {
    // this.selectedSkill = _.filter(this.skills, (v) => _.includes(selectedskillId, v.skillTrackMstrId));
    this.selectedCourseIdCollection = null;
    selectedskillId.forEach(element => {
      if (!this.selectedCourseIdCollection) {
        this.selectedCourseIdCollection = '?skillIds=' + element.skillTrackMstrId;
      } else {
        this.selectedCourseIdCollection = this.selectedCourseIdCollection + ',' + element.skillTrackMstrId;
      }
    });
    this.selectedSkill = this.localStorageService.get('selectedCourse');
    return this.selectedCourseIdCollection;
  }
  updateCourse() {

  }

  deleteCourse(skillData) {
    if (this.selectedSkill.length > 0) {
      this.selectedSkill.forEach((element, index) => {
        if (element.skillTrackMstrId === skillData.skillTrackMstrId) {
          this.selectedSkill.splice(index, 1);
        }
      });
      this.localStorageService.remove('selectedCourse');
      this.localStorageService.set('selectedCourse', this.selectedSkill);
      this.callGetSeachedData();
    }
    // this.selectedSkill
    // console.log(skillData);
    // _.remove(this.selectedSkill, obj => skillData.includes(obj.skillTrackMstrId));
  }
  displaySelectedCats() {
    if (this.showcatdispDiv === false) {
      this.showcatdispDiv = true;
    } else if (this.showcatdispDiv === true) {
      this.showcatdispDiv = false;
    }

  }

  execute() {
    this.employeeHttpService
      .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.toaster.error('Something went wrong, please try to submit again.');
        this.router.navigate(['employee/first-time']);
      }
      );
  };

  // submit the selected course and assessmnet

  submitCourseData() {
    const userInfo = this.localStorageService.get('userInfo')


    const skillIds = _.map(this.selectedSkill, function (row, index) {
      return _.omit(row, ['createdBy', 'createdDt', 'description', 'isSelected',
        'skillTrackName', 'status', 'updatedBy', 'updatedDt',]);
    });
    const courseBasedOnSkill = [];
    const assessmentData = {
      mandatory: false,
      userInfoMstrId: [userInfo['userInfoMstrId']],
      loggedInUserEmail: userInfo['email']
    };
    skillIds.forEach((element, index) => {
      const selfAssessmentBean = {
        // courseId: [],
        primaryAssessmentId: [],
        technicalAssessmentId: [],
        businessAssessmentId: [],
        skillTrackMstrId: Number
      };
      // this.allSelectedCourses.forEach(list => {
      //   if (element.skillTrackMstrId === list.skillTrackId) {
      //     selfAssessmentBean.courseId.push(list.courseDetailsId);
      //   }
      // });
      this.primarySelectedAssessment.forEach(list => {
        if (element.skillTrackMstrId === list.pgSkillTrackMstr.skillTrackMstrId) {
          selfAssessmentBean.primaryAssessmentId.push(Number(list.assessmentId));
        }
      });
      this.technicalSelectedAssessment.forEach(list => {
        if (element.skillTrackMstrId === list.skillTrackMstrId) {
          selfAssessmentBean.technicalAssessmentId.push(list.id);
        }
      });
      this.businessSelectedAssessment.forEach(list => {
        if (element.skillTrackMstrId === list.skillTrackMstrId) {
          selfAssessmentBean.businessAssessmentId.push(list.id);
        }
      });
      // this.learningSeletedPath.forEach(list => {
      //   if (element.skillTrackMstrId === list.skillTrackMstrId) {
      //     selfAssessmentBean.learningPathList.push(list.id);
      //   }
      // });
      selfAssessmentBean.skillTrackMstrId = element.skillTrackMstrId;
      if (this.learningSeletedPath.length > 0) {
        // assessmentData['learningPathList'] = _.map(this.learningSeletedPath, function (object) {
        //   return _.pick(object, ['id']);
        // });
        assessmentData['learningPathList'] = _.map(this.learningSeletedPath, _.partial(_.pick, _, ['id']));

      }
      if (selfAssessmentBean.businessAssessmentId.length > 0 || selfAssessmentBean.primaryAssessmentId.length > 0 || selfAssessmentBean.technicalAssessmentId.length > 0) {
        assessmentData['selfAssessmentBean'] = courseBasedOnSkill,
          courseBasedOnSkill.push(selfAssessmentBean);
      }
    });
    const courseBeam = [];

    this.allSelectedCourses.forEach(list => {
      const filteredCourse = {
        courseId: list.courseDetailsId,
        grpCourseId: null,
        lpId: null,
        loggedInUserEmail: this.employee.email,
        recommended: false
      };
      courseBeam.push(filteredCourse);
    });
    if (this.learningSeletedPath.length > 0) {
      this.learningSeletedPath.forEach(element => {
        const lpReq = {
          courseId: null,
          grpCourseId: null,
          lpId: element.id,
          loggedInUserEmail: this.employee.email,
          lpCourses: _.map(element.courseIds, 'id'),
          recommended: false
        };
        courseBeam.push(lpReq);
      });
    }

    /*This Request use to Cheange UserId for send multiple Id's*/
    const ReqJson = {
      userId : [userInfo['userInfoMstrId']],
      courseDetails: courseBeam
    }

    // submit selected course
    if (this.allSelectedCourses.length > 0 || this.learningSeletedPath.length > 0) {
      this.employeeHttpService.submitSelectedCourse(ReqJson).subscribe(responceData => {
        this.execute();
        this.router.navigate(['employee/dashboard']);

        if(responceData.message){
          this.toaster.success(responceData.message);
        } else if(responceData.errorBean.message === "Empty Course"){
          this.toaster.success(responceData.errorBean.message);

        }else {
          this.toaster.error(responceData.errorBean.message);

        }
      }, (error) => {
        this.toaster.error(error.error.errorBean.message);
      });
    }

    // submit selected assesment data
    if (this.primarySelectedAssessment.length > 0 || this.businessSelectedAssessment.length > 0 || this.technicalSelectedAssessment.length > 0 || this.learningSeletedPath.length > 0) {
      this.employeeHttpService.submitSelectedAssessment(assessmentData).subscribe(responceData => {
        this.execute();
        this.router.navigate(['employee/dashboard']);
        this.toaster.success(responceData.successMessage);
      }, (error) => {

        this.toaster.error(error.error.error.message);
      });
    }
    this.localStorageService.remove('selectedCourse');
    this.localStorageService.remove('serachedText');
  }

  SearchforCourses(event) {
    const val = event.target.value.toLowerCase();

    // filter our data
    const tempCourse = this.allReservedCourses.filter(function (d) {
      return d['courseName'].toLowerCase().indexOf(val) !== -1 || !val;
    });
    const tempBusiness = this.businessReservedAssessment.filter(function (d) {
      return d['usecaseTitle'].toLowerCase().indexOf(val) !== -1 || !val;
    });
    const tempTechnical = this.technicalReservedAssessment.filter(function (d) {
      return d['usecaseTitle'].toLowerCase().indexOf(val) !== -1 || !val;
    });
    const tempPrimary = this.primaryReservedAssessment.filter(function (d) {
      return d['assessmentDesc'].toLowerCase().indexOf(val) !== -1 || !val;
    });
    this.allCourses = tempCourse;
    this.primaryAssessment = tempPrimary;
    this.businessAssessment = tempBusiness;
    this.technicalAssessment = tempTechnical;
    this.tabDetails.forEach((data) => {
      if (data.containerText === 'Courses') {
        data.count = this.allCourses.length;
      } else if (data.containerText === 'Primary Assessment') {
        data.count = this.primaryAssessment.length;
      } else if (data.containerText === 'Technical Assessment') {
        data.count = this.technicalAssessment.length;
      } else if (data.containerText === 'Business Assessment') {
        data.count = this.businessAssessment.length;
      }
    });
  }
  viewCardDetails(courseId) {
    console.log(courseId);
    this.showCourseSelection = true;
    this.showArow = true;
    this.loader = true;
    this.employeeHttpService.getLearningPathCardDetails(courseId).subscribe(response => {
      console.log(response);
      this.learningPathCardDetails = response.learningPath;
      this.loader = false;
    }, (error) => {
      console.log(error);
    });

  }
  goToPrevPage() {
    if (this.localStorageService.get('serachedText')) {
      this.selectedSkill.forEach(element => {
        element.isSelected = true;
      });
      this.localStorageService.set('selectedCourse', this.selectedSkill);
    }
    this.router.navigate(['employee/first-time']);
  }
  nevBackWithoutRouting() {
    this.showCourseSelection = false;
    this.showArow = false;
  }
  changeRole(evnt) {
    this.roleStatus = !this.roleStatus;
  }
  closeNavDetails(event) {
    this.roleStatus = event;
  }

  openFeedModal(e){
    console.log(e);
    if(e == true){
      this.frmCandD = e
    }
  }

  closeFdModal(e){
    if(e == false){
      this.frmCandD = e;
    }
  }
}
