import { Component, OnInit, Input, EventEmitter, Output, ViewEncapsulation, ViewChild, ElementRef } from '@angular/core';
import { AuthService } from '../../../services/auth.service';
import { LocalStorageService } from 'angular-2-local-storage';
import { UserInfo } from '../../../models/userInfo.model';
import { EmployeeHttpService } from 'app/services/employee/employee-http.service';
import { EmployeeNavBarService } from '../../employee-dashboard/employee-nav-bar.service';
import { environment } from '../../../../environments/environment.dev';
@Component({
  selector: 'app-employee-task',
  templateUrl: './employee-task.component.html',
  styleUrls: ['./employee-task.component.scss'],
  providers: [EmployeeNavBarService],
  encapsulation: ViewEncapsulation.None
})
export class EmployeeTaskComponent implements OnInit {
  @ViewChild('searchword') searchword: ElementRef;
  @Input() showDashboard: boolean;
  @Output() getBackErrow = new EventEmitter<boolean>();
  imagelink: string;
  records: any;
  recordscopy: any;
  courserecords: any;
  allstatuscourserecords: any;
  allStatusLearningPathRecords: any;
  learningPathCount: number;
  allStatusLearningPathReservRecords: any;
  allstatuscourserecordscopy: any;
  AllcourserecordsCount: number;
  filterPrimaryusecase: any;
  filterTechnicalusecase: any;
  filterBusinessusecase: any;
  filterAllstatuscourserecords: any;
  filterAllStatusLearningPathRecords: any;
  primaryusecase: any;
  technicalusecase: any;
  businessusecase: any;
  primaryusecasecopy: any;
  technicalusecasecopy: any;
  businessusecasecopy: any;
  learningPathCollection: any;
  learningPathDetails: any;
  skills: any;
  statuscount: Statuscount;
  primarycount: number;
  technicalcount: number;
  businesscount: number;
  empData: UserInfo;
  filterword: string;
  previousfilterword: string;
  filterclickCount: number = 0;
  activefilter: string;
  filterdData: boolean;
  loader: boolean;
  img_path = environment.imageUrl+'/assets/img/Taflow/';
  constructor(private AuthService: AuthService,
    private employeeHttpService: EmployeeHttpService,
    private employeeNavBarService: EmployeeNavBarService,
    protected localStorageService: LocalStorageService, ) {
    this.empData = this.localStorageService.get('userInfo');
    this.showDashboard = true;
    this.filterdData = false;
    this.getAllSkills();
  }

  ngOnInit() {
    this.activefilter = 'initial';
    this.imagelink = environment.imageUrl+'/assets/img/employee/newdashboard/';
    this.defaultCount();
    this.primarycount = 0;
    this.technicalcount = 0;
    this.businesscount = 0;
    this.allstatuscourserecords = [];
    this.allStatusLearningPathRecords = [];
    this.AllcourserecordsCount = 0;
    this.delayAllSeviceCall();
    this.loader = true;
  }
  defaultCount() {
    this.statuscount = {
      'Overdue': 0,
      'ToDo': 0,
      'InProgress': 0,
      'UnderReview': 0,
      'ReviewCompleted': 0,
      'Done': 0
    };
  }
  delayAllSeviceCall() {
    setTimeout(() => {
      this.getAllLearningPath(this.empData.userInfoMstrId);
      this.getAllAssessment(this.empData.userInfoMstrId);
      this.getAllCourse(this.empData.userInfoMstrId);
    }, 1000);
  }
  getrecord(item) {
    console.log(item);
  }

  hideSlidingBtn() {
    this.getBackErrow.emit(true);
  }

  getAllAssessment(id) {
    this.AuthService.getEmployeeAssessmentStatus(id).then(resp => {
      this.records = resp;
      this.loader = false;
      this.recordscopy = [...resp];
      if (this.records) {
        this.filterdata();
      }
    }).catch(err => {
      console.log(err);
    });
  }

  getAllCourse(id) {
    this.AuthService.getEmployeeAllCourse(id).then(resp => {
      this.courserecords = resp.userCourseMapping;
      if (this.courserecords['In Progress'] !== undefined) {
        const inProgressCourse = this.courserecords['In Progress'].length > 0 && this.courserecords['In Progress'].map(obj => this.allstatuscourserecords.push(obj));
      }
      if (this.courserecords.Completed !== undefined) {
        const completedCourse = this.courserecords.Completed.length > 0 && this.courserecords.Completed.map(obj => this.allstatuscourserecords.push(obj));
      }
      if (this.courserecords.Open !== undefined) {
        const openCourse = this.courserecords.Open.length > 0 && this.courserecords.Open.map(obj => this.allstatuscourserecords.push(obj));
      }
      if (this.courserecords.Overdue !== undefined) {
        const overdueCourse = this.courserecords.Overdue.length > 0 && this.courserecords.Overdue.map(obj => this.allstatuscourserecords.push(obj));
      }

      this.allstatuscourserecordscopy = [...this.allstatuscourserecords];
      this.AllcourserecordsCount = this.allstatuscourserecords.length;
      this.getCountCourses(this.allstatuscourserecords);
      console.log(this.allstatuscourserecords);
    }).catch(err => {
      console.log(err);
    });
  }
  getAllLearningPath(userMasterId) {
    // OVERDUE, TODO, INPROGRESS, DONE
    console.log(userMasterId);
    this.employeeHttpService.getLearningPathOfEmp(userMasterId).subscribe(response => {
      this.learningPathCollection = response;
      if (this.learningPathCollection.INPROGRESS !== undefined) {
        const inProgressCourse = this.learningPathCollection.INPROGRESS.length > 0 && this.learningPathCollection.INPROGRESS.map(obj => this.allStatusLearningPathRecords.push(obj));
      }
      if (this.learningPathCollection.DONE !== undefined) {
        const completedCourse = this.learningPathCollection.DONE.length > 0 && this.learningPathCollection.DONE.map(obj => this.allStatusLearningPathRecords.push(obj));
      }
      if (this.learningPathCollection.TODO !== undefined) {
        const openCourse = this.learningPathCollection.TODO.length > 0 && this.learningPathCollection.TODO.map(obj => this.allStatusLearningPathRecords.push(obj));
      }
      if (this.learningPathCollection.OVERDUE !== undefined) {
        const overdueCourse = this.learningPathCollection.OVERDUE.length > 0 && this.learningPathCollection.OVERDUE.map(obj => this.allStatusLearningPathRecords.push(obj));
      }
      this.getCountFromLearningPath(this.allStatusLearningPathRecords);
      this.allStatusLearningPathReservRecords = [...this.allStatusLearningPathRecords]
      console.log(response);
      console.log(this.allStatusLearningPathRecords);
    }, (error) => {
      console.log(error);
    });
  }

  getCountCourses(record) {
    record.map(obj => {
      const status = obj.status.trim();
      if (status === 'Overdue') { this.statuscount.Overdue += 1; }
      if (status === 'Open') { this.statuscount.ToDo += 1; }
      if (status === 'Completed') { this.statuscount.Done += 1; }
      if (status === 'In Progress') { this.statuscount.InProgress += 1; }
    });
  }

  getCountFromLearningPath(record) {
    record.map(obj => {
      const status = obj.userStatus.trim();
      if (status === 'OVERDUE') { this.statuscount.Overdue += 1; }
      if (status === 'TODO') { this.statuscount.ToDo += 1; }
      if (status === 'DONE') { this.statuscount.Done += 1; }
      if (status === 'INPROGRESS') { this.statuscount.InProgress += 1; }
    });
  }

  getCountAssessment(record) {
    record.map(obj => {
      if (obj.assessmentStatus === 'ASSIGNED') { this.statuscount.ToDo += 1; }
      if (obj.assessmentStatus === 'OVERDUE') { this.statuscount.Overdue += 1; }
      if (obj.assessmentStatus === 'INPROGRESS') { this.statuscount.InProgress += 1; }
      if (obj.assessmentStatus === 'REVIEW_PENDING') { this.statuscount.UnderReview += 1; }
      if (obj.assessmentStatus === 'UNDER_REVIEW') { this.statuscount.UnderReview += 1; }
      if (obj.assessmentStatus === 'REVIEW_COMPLETED') { this.statuscount.ReviewCompleted += 1; }
      if (obj.assessmentStatus === 'DONE') { this.statuscount.Done += 1; }
    });
  }

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

  filterdata() {
    console.log(this.records);
    this.getCountAssessment(this.records);
    this.primaryusecase = this.records.filter(obj => obj.eventMstrId === 1);
    this.technicalusecase = this.records.filter(obj => obj.eventMstrId === 2);
    this.businessusecase = this.records.filter(obj => obj.eventMstrId === 3);
    this.primaryusecasecopy = [...this.primaryusecase];
    this.technicalusecasecopy = [...this.technicalusecase];
    this.businessusecasecopy = [...this.businessusecase];
    this.primarycount = this.primaryusecase.length;
    this.technicalcount = this.technicalusecase.length;
    this.businesscount = this.businessusecase.length;
  }

  insearch(searchword) {
    const val = searchword.value;
    if (val.length >= 2) {
      this.filterdData = true;
      this.activefilter = '';
      this.allstatuscourserecords = this.allstatuscourserecordscopy.filter(d => {
        // x.pgCourseDetails.courseName.toLowerCase().includes(val.toLowerCase());
        return d.pgCourseDetails.courseName.toLowerCase().indexOf(val) !== -1 || !val;
      });
      this.AllcourserecordsCount = this.allstatuscourserecords.length;
      // if (this.primaryusecasecopy !== undefined) {
      this.primaryusecase = [...this.primaryusecasecopy].filter(d => {
        if (d.primary.length > 0) {
          // d.primary[0].assessmentName.toLowerCase().includes(kw.toLowerCase());
          return d.primary[0].assessmentName.toLowerCase().indexOf(val) !== -1 || !val;
        }
      });
      // }
      // if (this.technicalusecasecopy !== undefined) {
      this.technicalusecase = [...this.technicalusecasecopy].filter(d => {
        if (d.technical.length > 0) {
          // obj.technical[0].usecaseTitle.toLowerCase().includes(kw.toLowerCase());
          return d.technical[0].usecaseTitle.toLowerCase().indexOf(val) !== -1 || !val;
        }
      });
      // if (this.businessusecasecopy[0] !== undefined) {
      this.businessusecase = [...this.businessusecasecopy].filter(d => {
        if (d.business.length > 0) {
          // obj.business[0].usecaseTitle.toLowerCase().includes(kw.toLowerCase());
          return d.business[0].usecaseTitle.toLowerCase().indexOf(val) !== -1 || !val;
        }
      });
      // }
      // if (this.allStatusLearningPathReservRecords.length > 0) {
      this.allStatusLearningPathRecords = [...this.allStatusLearningPathReservRecords].filter(d => {
        // obj.name.toLowerCase().includes(kw.toLowerCase());
        return d.name.toLowerCase().indexOf(val) !== -1 || !val;
      });
      this.filterPrimaryusecase = [...this.primaryusecase];
      this.filterTechnicalusecase = [...this.technicalusecase];
      this.filterBusinessusecase = [...this.businessusecase];
      this.filterAllstatuscourserecords = [...this.allstatuscourserecords];
      this.filterAllStatusLearningPathRecords = [...this.allStatusLearningPathRecords];
      this.defaultCount();
      this.getCountCourses(this.filterAllstatuscourserecords);
      this.getCountAssessment(this.filterPrimaryusecase);
      this.getCountAssessment(this.filterTechnicalusecase);
      this.getCountAssessment(this.filterBusinessusecase);
      this.getCountFromLearningPath(this.filterAllStatusLearningPathRecords);
      // }
    } else {
      this.defaultCount();
      this.activefilter = '';
      this.filterdData = false;
      this.allstatuscourserecords = [...this.allstatuscourserecordscopy];
      this.primaryusecase = [...this.primaryusecasecopy];
      this.technicalusecase = [...this.technicalusecasecopy];
      this.businessusecase = [...this.businessusecasecopy];
      this.allStatusLearningPathRecords = [...this.allStatusLearningPathReservRecords];
      this.getCountCourses(this.allstatuscourserecords);
      this.getCountAssessment(this.primaryusecase);
      this.getCountAssessment(this.technicalusecase);
      this.getCountAssessment(this.businessusecase);
      this.getCountFromLearningPath(this.allStatusLearningPathRecords);
      this.primarycount = this.primaryusecasecopy.length;
      this.technicalcount = this.technicalusecasecopy.length;
      this.businesscount = this.businessusecasecopy.length;
      this.learningPathCount = this.allstatuscourserecordscopy.length;
    }
  }
  learningPathCardDetails(event) {
    const id = String(event) + '/' + String(this.empData.userInfoMstrId);
    console.log(id);
    // console.log(courseId);
    // this.showCourseSelection = true;
    // this.showArow = true;
    // this.loader = true;
    // this.getBackErrow.emit(true);
    this.employeeHttpService.getLearningPathCardDetails(id).subscribe(response => {
      console.log(response);
      this.learningPathDetails = response.learningPath;
      this.showDashboard = false;
      // this.loader = false;
    }, (error) => {
      console.log(error);
    });
  }
  statusfilter(data) {
    // this.searchword.nativeElement.value = '';
    this.filterword = data;
    this.filterword === 'In Progress' ? this.filterword = 'INPROGRESS' : '';
    this.filterword === 'To Do' ? this.filterword = 'ASSIGNED' : '';
    this.filterword === 'Under Review' ? this.filterword = 'UNDER_REVIEW' : '';
    this.filterword === 'Review Completed' ? this.filterword = 'REVIEWING_COMPLETED' : '';
    this.filterword === 'REVIEWING_COMPLETED' ? this.filterword = 'Review Completed' : '';
    this.filterword === 'Review Completed' ? this.filterword = 'REVIEW_COMPLETED' : '';
    this.filterword === 'Done' ? this.filterword = 'DONE' : '';

    if (this.filterdData) {
      if (this.filterword !== this.previousfilterword || this.filterclickCount === 0) {
        this.filterclickCount += 1;
        this.activefilter = data;
        this.previousfilterword = this.filterword;
        this.AllcourserecordsCount = this.allstatuscourserecords.length;
        this.allStatusLearningPathRecords = this.filterAllStatusLearningPathRecords.filter(x => x.userStatus.trim() === 'DONE');
        if (this.filterword === 'UNDER_REVIEW') {
          if (this.filterPrimaryusecase.length === 0) {
            this.primaryusecase = this.filterPrimaryusecase.filter(x => (x.assessmentStatus.toLowerCase().trim() === 'REVIEW_PENDING'.toLowerCase().trim()) || (x.assessmentStatus.toLowerCase().trim() === 'UNDER_REVIEW'.toLowerCase().trim()));
          }
          if (this.filterTechnicalusecase.length === 0) {
            this.technicalusecase = this.filterTechnicalusecase.filter(x => (x.assessmentStatus.toLowerCase().trim() === 'REVIEW_PENDING'.toLowerCase().trim()) || (x.assessmentStatus.toLowerCase().trim() === 'UNDER_REVIEW'.toLowerCase().trim()));
          }
          if (this.filterBusinessusecase.length === 0) {
            this.businessusecase = this.filterBusinessusecase.filter(x => (x.assessmentStatus.toLowerCase().trim() === 'REVIEW_PENDING'.toLowerCase().trim()) || (x.assessmentStatus.toLowerCase().trim() === 'UNDER_REVIEW'.toLowerCase().trim()));
          }
        } else {
          this.primaryusecase = this.filterPrimaryusecase.filter(x => x.assessmentStatus.toLowerCase().trim() === this.filterword.toLowerCase().trim());
          this.technicalusecase = this.filterTechnicalusecase.filter(x => x.assessmentStatus.toLowerCase().trim() === this.filterword.toLowerCase().trim());
          this.businessusecase = this.filterBusinessusecase.filter(x => x.assessmentStatus.toLowerCase().trim() === this.filterword.toLowerCase().trim());  
        }
        this.primarycount = this.primaryusecase.length;
        this.technicalcount = this.technicalusecase.length;
        this.businesscount = this.filterBusinessusecase.length;
        this.learningPathCount = this.allStatusLearningPathRecords.length;

        if (data === 'Done') {
          const filterText = 'Completed ';
          this.allstatuscourserecords = this.filterAllstatuscourserecords.filter(x => x.status.toLowerCase().trim() === 'Completed'.toLowerCase().trim());
          this.allStatusLearningPathRecords = this.filterAllStatusLearningPathRecords.filter(x => x.userStatus.trim() === 'DONE');
        } else if (data === 'To Do') {
          const filterText = 'Open';
          this.allstatuscourserecords = this.filterAllstatuscourserecords.filter(x => x.status.toLowerCase().trim() === 'Open'.toLowerCase().trim());
          this.allStatusLearningPathRecords = this.filterAllStatusLearningPathRecords.filter(x => x.userStatus.trim() === 'TODO');
        } else if (data === 'Overdue') {
          const filterText = 'Overdue';
          this.allstatuscourserecords = this.filterAllstatuscourserecords.filter(x => x.status.toLowerCase().trim() === 'Overdue'.toLowerCase().trim());
          this.allStatusLearningPathRecords = this.filterAllStatusLearningPathRecords.filter(x => x.userStatus.trim() === 'OVERDUE'.trim());
        } else if (data === 'In Progress') {
          const filterText = 'INPROGRESS';
          this.allstatuscourserecords = this.filterAllstatuscourserecords.filter(x => x.status.toLowerCase().trim() === 'In Progress'.toLowerCase().trim());
          this.allStatusLearningPathRecords = this.filterAllStatusLearningPathRecords.filter(x => x.userStatus.trim() === 'INPROGRESS');
        } else {
          this.allstatuscourserecords = this.filterAllstatuscourserecords.filter(x => x.status.toLowerCase().trim() === this.filterword.toLowerCase().trim());
          this.allStatusLearningPathRecords = [];
        }

      } else {
        this.filterclickCount = 0;
        this.activefilter = '';
        this.primaryusecase = this.filterPrimaryusecase;
        this.technicalusecase = this.filterTechnicalusecase;
        this.businessusecase = this.filterBusinessusecase;
        this.allstatuscourserecords = this.filterAllstatuscourserecords;
        this.allStatusLearningPathRecords = this.filterAllStatusLearningPathRecords;
        this.primarycount = this.filterPrimaryusecase.length;
        this.businesscount = this.filterBusinessusecase.length;
        this.technicalcount = this.filterTechnicalusecase.length;
        this.learningPathCount = this.filterAllStatusLearningPathRecords.length;
      }
    } else {
      if (this.filterword !== this.previousfilterword || this.filterclickCount === 0) {
        this.filterclickCount += 1;
        this.activefilter = data;
        this.previousfilterword = this.filterword;
        this.AllcourserecordsCount = this.allstatuscourserecords.length;
        if (this.filterword === 'UNDER_REVIEW') {
          // if (this.primaryusecase.length === 0) {
            this.primaryusecase = this.primaryusecasecopy.filter(x => (x.assessmentStatus.toLowerCase().trim() === 'REVIEW_PENDING'.toLowerCase().trim()) || (x.assessmentStatus.toLowerCase().trim() === 'UNDER_REVIEW'.toLowerCase().trim()));
          // }
          // if (this.technicalusecase.length === 0) {
            this.technicalusecase = this.technicalusecasecopy.filter(x => (x.assessmentStatus.toLowerCase().trim() === 'REVIEW_PENDING'.toLowerCase().trim()) || (x.assessmentStatus.toLowerCase().trim() === 'UNDER_REVIEW'.toLowerCase().trim()));
          // }
          // if (this.businessusecase.length === 0) {
            this.businessusecase = this.businessusecasecopy.filter(x => (x.assessmentStatus.toLowerCase().trim() === 'REVIEW_PENDING'.toLowerCase().trim()) || (x.assessmentStatus.toLowerCase().trim() === 'UNDER_REVIEW'.toLowerCase().trim()));
          // }
        } else {
          this.primaryusecase = this.primaryusecasecopy.filter(x => x.assessmentStatus.toLowerCase().trim() === this.filterword.toLowerCase().trim());
          this.technicalusecase = this.technicalusecasecopy.filter(x => x.assessmentStatus.toLowerCase().trim() === this.filterword.toLowerCase().trim());
          this.businessusecase = this.businessusecasecopy.filter(x => x.assessmentStatus.toLowerCase().trim() === this.filterword.toLowerCase().trim());  
        }
        this.primarycount = this.primaryusecasecopy.length;
        this.technicalcount = this.technicalusecasecopy.length;
        this.businesscount = this.businessusecasecopy.length;
        this.learningPathCount = this.allstatuscourserecordscopy.length;

        if (data === 'Done') {
          const filterText = 'Completed ';
          this.allstatuscourserecords = this.allstatuscourserecordscopy.filter(x => x.status.toLowerCase().trim() === 'Completed'.toLowerCase().trim());
          this.allStatusLearningPathRecords = this.allStatusLearningPathReservRecords.filter(x => x.userStatus.trim() === 'DONE');
        } else if (data === 'To Do') {
          const filterText = 'Open';
          this.allstatuscourserecords = this.allstatuscourserecordscopy.filter(x => x.status.toLowerCase().trim() === 'Open'.toLowerCase().trim());
          this.allStatusLearningPathRecords = this.allStatusLearningPathReservRecords.filter(x => x.userStatus.trim() === 'TODO');
        } else if (data === 'Overdue') {
          const filterText = 'Overdue';
          this.allstatuscourserecords = this.allstatuscourserecordscopy.filter(x => x.status.toLowerCase().trim() === 'Overdue'.toLowerCase().trim());
          this.allStatusLearningPathRecords = this.allStatusLearningPathReservRecords.filter(x => x.userStatus.trim() === 'OVERDUE'.trim());
        } else if (data === 'In Progress') {
          const filterText = 'INPROGRESS';
          this.allstatuscourserecords = this.allstatuscourserecordscopy.filter(x => x.status.toLowerCase().trim() === 'In Progress'.toLowerCase().trim());
          this.allStatusLearningPathRecords = this.allStatusLearningPathReservRecords.filter(x => x.userStatus.trim() === 'INPROGRESS');
        } else {
          this.allstatuscourserecords = this.allstatuscourserecords.filter(x => x.status.toLowerCase().trim() === this.filterword.toLowerCase().trim());
          this.allStatusLearningPathRecords = [];
        }

      } else {
        this.filterclickCount = 0;
        this.activefilter = '';
        this.allstatuscourserecords = [...this.allstatuscourserecordscopy];
        this.primaryusecase = [...this.primaryusecasecopy];
        this.technicalusecase = [...this.technicalusecasecopy];
        this.businessusecase = [...this.businessusecasecopy];
        this.allStatusLearningPathRecords = [...this.allStatusLearningPathReservRecords];
        this.defaultCount();
        this.getCountCourses(this.allstatuscourserecords);
        this.getCountAssessment(this.primaryusecase);
        this.getCountAssessment(this.technicalusecase);
        this.getCountAssessment(this.businessusecase);
        this.getCountFromLearningPath(this.allStatusLearningPathRecords);
      }
    }
  }
}
export interface Statuscount {
  'Overdue': number;
  'ToDo': number;
  'InProgress': number;
  'UnderReview': number;
  'ReviewCompleted': number;
  'Done': number;
}
