import { Component, OnInit, ViewEncapsulation, OnChanges } from '@angular/core';
import { EmployeeHttpService } from 'app/services/employee/employee-http.service';
import { LocalStorageService } from 'angular-2-local-storage';
import { Router, ActivatedRoute } from '@angular/router';
import { Subject } from 'rxjs/Subject';
import { EmployeeReview } from '../../../models/employee.model';
import * as Moment from 'moment';
import { environment } from '../../../../environments/environment.dev';

@Component({
  selector: 'app-employee-review',
  templateUrl: './employee-review.component.html',
  styleUrls: ['./employee-review.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class EmployeeReviewComponent implements OnInit, OnChanges {

  imagelink: string;
  reviewStatusCount: {};
  userInfoMstrId: string;
  activereviewfilter: '';
  private reviewStatus: string[] = ['To Do', 'Overdue', 'Done'];
  gridData: any[];
  reviewData: EmployeeReview[];
  gridView = true;
  private $destroyed = new Subject();
  loader = false;
  gridDataEmpty = false;
  filterStatus = '';
  private defaultStatus = 'PENDING,PASSED,REJECTED,DONE';

  constructor(
    private employeeHttpService: EmployeeHttpService,
    private localStorageService: LocalStorageService,
    private router: Router,
    private route: ActivatedRoute
  ) {
    const empData = this.localStorageService.get('userInfo');
    if (empData['userInfoMstrId']) {
      this.userInfoMstrId = empData['userInfoMstrId'];
    }
  }

  ngOnInit() {
    this.imagelink = environment.imageUrl+'/assets/img/employee/newdashboard/';
    this.reviewStatusCount = {
      'Overdue': 0,
      'ToDo': 0,
      'Done': 0
    };
    //  this.userInfoMstrId = '3';
    this.getReviewDetails();
    this.getReviewDetailsList();
  }

  ngOnChanges() {

  }

  toggleView() {
    this.gridView = !this.gridView;
  }

  getReviewDetails() {
    this.employeeHttpService.getEmployeeReviewDetails(this.userInfoMstrId, this.defaultStatus).takeUntil(this.$destroyed)
      .subscribe(data => {
        this.reviewData = data;
        this.getReviewCount();
      });
  }

  getReviewDetailsList() {
    this.gridData = [];
    this.loader = true;
    this.employeeHttpService.getEmployeeReviewDetailsList(this.userInfoMstrId, this.defaultStatus).takeUntil(this.$destroyed)
      .subscribe(data => {
        this.gridData = data;
        if (this.filterStatus !== '') {
            this.filterGridData();
        }
        if (this.gridData.length > 0) {
          this.gridDataEmpty = true;
        }
        this.loader = false;
      });
  }

  getReviewCount() {
    this.reviewData.forEach(review => {
      if (this.getStatus(review.status) === 'To Do') {
        if (this.isOverdue(review)) {
          this.reviewStatusCount['Overdue']++;
        } else {
          this.reviewStatusCount['ToDo']++;
        }
      } else {
        this.reviewStatusCount[this.getStatus(review.status)] = this.reviewStatusCount[this.getStatus(review.status)] + 1;
      }
    });
  }

  getInitials(fullName: string) {
    if (fullName) {
      return fullName.replace(/\W*(\w)\w*/g, '$1').toUpperCase();
    }
  }

  getStatus(type) {
    const status = {
      'PENDING': 'To Do',
      'PASSED': 'Done',
      'REJECTED': 'Done',
      'DONE': 'Done',
      'default': 'Invalid'
    };
    return status[type] || status['default'];
  }

  getApiStatus(type) {
    const status = {
      'To Do': 'PENDING',
      'Done': 'PASSED,REJECTED,DONE',
      'Overdue': 'PENDING',
      'default': 'Invalid'
    };
    return status[type] || status['default'];
  }

  statusfilter(data: string) {
    this.defaultStatus = this.getApiStatus(data);
    this.getReviewDetailsList();
    this.filterStatus = data;
  }

  isOverdue(review: EmployeeReview) {
    const calculatedDate = Moment(review.updatedDate, 'YYYY-MM-DD').add(review.overdueDays, 'days').format('YYYY-MM-DD');
    const currentDate = Moment(Moment.now()).format('YYYY-MM-DD');
    return Moment(calculatedDate).isBefore(currentDate);
  }

  filterGridData() {
    this.gridData.forEach(assessmentDetails => {
      assessmentDetails.userDetails.forEach((user, index) => {
        if (user.assessmentDetails.length > 0) {
          user.assessmentDetails.forEach((assessment, assessmentIndex) => {
            if (this.filterStatus === 'Overdue') {
              if (!this.isOverdue(assessment)) {
                user.assessmentDetails.splice(assessmentIndex, 1);
              }
            } else if (this.filterStatus === 'To Do') {
              if (this.isOverdue(assessment)) {
                user.assessmentDetails.splice(assessmentIndex, 1);
              }
            }
          });
        }
      });
    });
    // console.log('filteredData ' + JSON.stringify(this.gridData));
    this.cleanUpData();
  }

  cleanUpData() {
    let userArray = [];
    this.gridData.forEach((assessmentDetails, assessmentDataIndex) => {
      assessmentDetails.userDetails.forEach((user, index) => {
        if (user.assessmentDetails.length !== 0) {
          userArray.push(user);
        }
      });
      assessmentDetails.userDetails = userArray;
      userArray = [];
      if (assessmentDetails.userDetails.length === 0) {
        this.gridData.splice(assessmentDataIndex);
      }
    });
    // console.log('cleaned up data' + JSON.stringify(this.gridData));
  }
}
