import {Component, OnInit, Inject, HostListener} from '@angular/core';
import { UserInfo } from 'app/models/userInfo.model';
import { AuthService } from 'app/services/auth.service';
import { LocalStorageService } from 'angular-2-local-storage';
import { NavBarService } from '../../../pgm/pgm.service';
import { EmployeeHttpService } from 'app/services/employee/employee-http.service';
import { EmployeeService } from 'app/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 {IMyDpOptions} from 'mydatepicker';
import {BulkUploadFileService} from "../../../ta/ta-bulk-upload/bulk-upload-file.service";
import { environment } from '../../../../environments/environment.dev';

@Component({
  selector: 'app-select-learning-path',
  templateUrl: './select-learning-path.component.html',
  styleUrls: ['./select-learning-path.component.scss']
})
export class SelectLearningPathComponent implements OnInit {

  private $destroyed = new Subject();
  documentDetails;
  selectedTab: number;
  showcatdispDiv: boolean = false;
  coursesLists;
  allCourses;
  learningPath;
  primaryAssessment;
  technicalAssessment;
  businessAssessment;
  allReservedCourses;
  primaryReservedAssessment;
  technicalReservedAssessment;
  businessReservedAssessment;
  allSelectedCourses: any = [];
  primarySelectedAssessment: any = [];
  technicalSelectedAssessment: any = [];
  businessSelectedAssessment: any = [];
  learningPathSelected: any = [];
  skillMstrIds;
  selectedCoursesDetails: any = [];
  selectedCourses: any = [];
  selectedCoursesSetDueDate: any = [];
  selectedLearningPathSetDueDate: any = [];
  selectedCourseIdCollection: string;
  skills: any;
  selectedSkill: any = [];
  empLists: any = [];
  loader = true;
  currentPageData: { title: string, back: string };
  onlyOneRole: boolean;
  public currentPageNumber = 0;
  img_path = environment.imageUrl+'/assets/img/Taflow/';
  initials = '';
  employee: any = {};
  tabDetails = [
    { className: 'first', Id: 2, containerText: 'Learning Path', count: 0 },
  ];
  empData: {
    accessToken: any,
    loginType: any,
    fullName: any,
    firstName: any,
    userInfoMstrId: any,
    roleName: any,
    roles: any,
    skills: any,
    location: any,
    email: any
  };
  learningPathCardDetails;
  learningPathData = false;
  afterSelect = true;
  selectedEmployeeDetails: any = [];
  selectedEmployee: any = [];
  BeforeSelectCls = "col-lg-12";
  AfterSelectCls = "col-lg-0";
  UperBeforSelectCls = "col-lg-8";
  UperAfterSelectCls = "col-lg-4";

  myDatePickerOptions: IMyDpOptions = {
    // other options...
    dateFormat: 'dd-mm-yyyy',
    openSelectorTopOfInput : true,
    inline: false,
  };
  public model: any = 'Due date';

  private placeholder: string = 'Select Due date';

  dueDate: any
  //img_path = '../assets/img/Taflow/';
  dragAreaClass: string = 'dragarea';

  dueDateContainer = true;
  uploadContainer = false;
  searchContainer = false;
  employeeListContainer = false
  uploadedEmployeeList = false
  confirmationContainer = false

  courseAssigned = false;
  assessmentAssigned = false;
  empLists1 = [];
  imageUrl = environment.imageUrl;

  constructor( @Inject(DOCUMENT) document,
               protected localStorageService: LocalStorageService,
               private navBarService: NavBarService,
               private employeeHttpService: EmployeeHttpService,
               private employeeService: EmployeeService,
               private route: ActivatedRoute,
               private AuthService: AuthService,
               private toaster: ToastsManager,
               private router: Router,
               private bulkUploadFileService: BulkUploadFileService,
  ) {
    this.navBarService.setCurrentPage(4);
    console.log(document);
    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.empData = this.localStorageService.get('userInfo');
    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') {
        data.count = courseList.learningPath.length;
      }
    });
  }

  selectCourse(course: any = {}, category) {
    console.log(category)
    console.log(course)
    if (course.selected) {
      course.selected = false;
      if (category === 'Learning Path') {
        this.learningPathSelected = this.learningPathSelected.filter(item => item.id !== course.id);

      }
    } else {
      course.selected = true;
      if (category === 'Learning Path') {
        this.learningPathSelected.push(course)
      }
    }
   // console.log(this.selectedCourses, 'selectedCourses');
    console.log(this.learningPathSelected, 'selectedCoursesDetails');
  }

  setDueDatelearningPath(path) {

    console.log(path);

    if (path.selected) {

      this.selectedLearningPathSetDueDate = this.selectedLearningPathSetDueDate.filter(item => item.id !== path.id);


    } else {
      this.selectedLearningPathSetDueDate.push(path);
    }

    this.learningPathSelected.forEach(item => {
      console.log(item)
      if(item.id === path.id) {
        item.selected = !path.selected;
        // item.dueDate = undefined;
      }
    })

    console.log(this.selectedLearningPathSetDueDate, 'selectedCoursesSetDueDate');

  }
  onDateChanged(evnt){
    console.log(evnt.formatted);
    this.dueDate = evnt.formatted
    this.learningPathSelected.forEach(allCourse => {
      this.selectedLearningPathSetDueDate.forEach(dueDateCourse => {
        if(allCourse.id == dueDateCourse.id) {
            allCourse.selected = false;
          allCourse.dueDate = this.dueDate;
        }
      })
    })

    this.selectedLearningPathSetDueDate = [];
  }


  assignCourseAssessment() {

    let setDateCoure = [] = this.learningPathSelected.filter(item => item.dueDate);

    console.log(setDateCoure)
    if(setDateCoure.length !== this.learningPathSelected.length){
      this.toaster.error( "Please set Due Date All Learning Path");
    } else {

      this.BeforeSelectCls = "col-lg-8";
      this.AfterSelectCls = "col-lg-4 aftrSlctCls";
      this.UperBeforSelectCls = "col-lg-4";
      this.UperAfterSelectCls = "col-lg-3";
      this.employeeListContainer = true;
      this.dueDateContainer = false;
    }
  }


  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;
    }

  }



  selectedLearningPath() {
    console.log(this.learningPathSelected);
    this.afterSelect = false;
    this.learningPathSelected.forEach(item => {
      item.selected = false;
      item.dueDate = undefined;
    });

  }
  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;
      }
    })
  }

  goToPrevPage() {
    if (this.localStorageService.get('serachedText')) {
      this.selectedSkill.forEach(element => {
        element.isSelected = true;
      });
      this.localStorageService.set('selectedCourse', this.selectedSkill);
    }
    this.router.navigate(['talent-transformation/employee/CourseAndAssessment']);
  }



  Initials(cString) {
    if (cString) {
      return cString.replace(/\W*(\w)\w*/g, '$1').toUpperCase();
    }
  }


  onSelectionChange (emp, value, evnt) {
    console.log('selected Employeeee Eventsssssssss', evnt);
    console.log(emp, 'selected Employeeee', value);

    if (evnt.target.checked) {
      this.selectedEmployee = Object.assign({}, this.selectedEmployee, emp);
      this.selectedEmployeeDetails.push(emp);
      console.log(this.selectedEmployeeDetails, 'selected EmployeeDetails');
    } else {
      this.selectedEmployeeDetails = this.selectedEmployeeDetails.filter(item => item.adId !== emp.adId)
      console.log(this.selectedEmployeeDetails, 'selected EmployeeDetails');

    }
  }

  empAssignClick(params){
    if (params == 'search') {
      this.uploadContainer = false;
      this.searchContainer = true;
      this.employeeListContainer = false;
    } else {
      this.uploadContainer = true;
      this.searchContainer = false;
      this.employeeListContainer = false;
    }
    this.empLists =[]
  }

  changeTask () {
    this.uploadContainer = true;
    this.searchContainer = false;
    this.employeeListContainer = false;
  }

  keySearch (param) {
    // console.log(param, 'param');
    if (param) {
      this.employeeHttpService.quicksearchEmployee({filterParam: param}).takeUntil(this.$destroyed)
        .subscribe(data => {
          // console.log(JSON.stringify(data), 'SearchEmployee');
          // if (data.userList.length !== 0) {
          // this.empLists = data.userList;
          //   this.confirmationContainer = true;
          // }
          this.empLists1 = data;
          this.confirmationContainer = true;
          this.empLists = [];
        });
    } else {
      this.empLists = [];
    }
  }

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


  onFileChange(event) {
    let files = event.target.files;
    this.saveFiles(files);
  }
  @HostListener('dragover', ['$event']) onDragOver(event) {
    this.dragAreaClass = "droparea";
    event.preventDefault();
  }
  @HostListener('dragenter', ['$event']) onDragEnter(event) {
    this.dragAreaClass = "droparea";
    event.preventDefault();
  }
  @HostListener('dragend', ['$event']) onDragEnd(event) {
    this.dragAreaClass = "dragarea";
    event.preventDefault();
  }
  @HostListener('dragleave', ['$event']) onDragLeave(event) {
    this.dragAreaClass = "dragarea";
    event.preventDefault();
  }
  @HostListener('drop', ['$event']) onDrop(event) {
    this.dragAreaClass = "dragarea";
    event.preventDefault();
    event.stopPropagation();
    var files = event.dataTransfer.files;
    this.saveFiles(files);
  }

  saveFiles(files) {
    console.log(files)


    if (files.length > 0) {
      let formData: FormData = new FormData();
      for (var j = 0; j < files.length; j++) {
        formData.append("file[]", files[j], files[j].name);
      }
      // var parameters = {
      //     projectId: this.projectId,
      //     sectionId: this.sectionId
      // }
      //this.bulkUploadFileService.upload(formData, parameters)
      this.bulkUploadFileService.EmployeUpload(formData)
        .subscribe(
          uplResult => {
            console.log(uplResult);
            this.empLists = uplResult.userList
            console.log(this.empLists);
            this.uploadedEmployeeList = true;
            this.confirmationContainer = true;

          },
          error => {
            console.log(JSON.stringify(error));

          });
    }
  }

  submitCourseAssessment() {

    if(this.selectedEmployeeDetails.length == 0){
      this.toaster.error('Please Select Employee');
    } else {

      this.assignAssessment();
    }

  }



  assignCourse(course,empList) {

    var reqJson = []
    if(course.length !== 0) {

      course.forEach(list => {
        empList.forEach(user => {

          const filteredCourse = {
            userId: user.userInfoMstr.userInfoMstrId,
            dueDate: list.dueDate,
            courseId: list.courseDetailsId,
            grpCourseId: null,
            recommended: true
          };
          reqJson.push(filteredCourse);
        });
      });

      console.log(reqJson);

      this.AuthService.addUserCourses(reqJson).then(resp => {


        if (resp.status == 'error') {
          console.log(resp);
          this.toaster.error(resp.message);

        } else {
          console.log(resp);
          this.courseAssigned = true;
          this.BeforeSelectCls = "col-lg-8 changeOpacity";
        }
      }).catch(err => {
        console.log(err);
      })

    }

  }
  assignAssessment() {



    const skillIds = _.map(this.selectedSkill, function (row, index) {
      return _.omit(row, ['createdBy', 'createdDt', 'description', 'isSelected',
        'skillTrackName', 'status', 'updatedBy', 'updatedDt',]);
    });
    const courseBasedOnSkill = [];
    const users = [];

      this.selectedEmployeeDetails.forEach(user => {
        console.log(user)
        if(user.userInfoMstrId) {
          users.push(user.userInfoMstrId);
        } else {
          users.push(user.userInfoMstr.userInfoMstrId);
        }
      });
    const assessmentData = {
      "mandatory": true,
      "dueDate": "2018-10-01T09:45:00.000",
      "userInfoMstrId": users,
      "loggedInUserEmail": this.empData.email,
    };
    assessmentData['learningPathList'] = _.map(this.learningPathSelected, _.partial(_.pick, _, ['id']));
    console.log(assessmentData);
      const courseBeam = [];
        this.learningPathSelected.forEach(element => {
          if(element.courseIds){
          const lpReq = {
            courseId: null,
            loggedInUserEmail: this.empData.email,
            lpId: element.id,
            lpCourses: _.map(element.courseIds, 'id'),
            recommended: true
          };
          courseBeam.push(lpReq);
        }
        });

    const ReqJson = {
      userId : users,
      courseDetails: courseBeam
    }
      Promise.all([
        this.AuthService.selfAssessment(assessmentData),
        this.AuthService.addUserCourses(ReqJson)]
      )
        .then(arr => {
          console.log(arr[0],'selfAssessment');
          console.log(arr[1],'addUserCourses');
          if (arr[1].status == 'error' || arr[0].status == 'error') {
          if ( arr[0].status == 'error') {
            this.toaster.error(arr[0].message);
          } if ( arr[1].status == 'error') {
            this.toaster.error(arr[1].message);
          }
          } else {
            this.assessmentAssigned = true;
            this.confirmationContainer = false;
            this.BeforeSelectCls = "col-lg-8 changeOpacity";
          }
        }).catch (err => {
        console.log("Error for this :",err)
      });
  }


  viewLearningPath(id) {

    console.log(id);
    this.employeeHttpService.getLearningPathCardDetails(id).subscribe(response => {
      console.log(response);
      this.learningPathCardDetails = response.learningPath;
      this.learningPathData = true;
    }, (error) => {
      console.log(error);
    });
  }

  closeLP() {
    this.learningPathData = !this.learningPathData;
  }


}
