import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  HostListener
} from '@angular/core';
import { NavBarService } from '../ta.service';
import { BulkUploadFileService } from './bulk-upload-file.service';
import { LocalStorageService } from 'angular-2-local-storage';
// import * as _ from 'underscore';
import { PagerService } from '../../admin/inner-admin-pages/right-admin-panel/user-mgmt/_services/index';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { Router, ActivatedRoute } from '@angular/router';
import _ from 'lodash';
import { environment } from '../../../environments/environment.dev';

@Component({
  selector: 'app-ta-bulk-upload',
  templateUrl: './ta-bulk-upload.component.html',
  styleUrls: ['./ta-bulk-upload.component.scss']
})
export class TaBulkUploadComponent implements OnInit {
  title = 'Add Candidate - Bulk Upload';
  errors: Array<string> = [];
  dragAreaClass: string;
  @Input()
  projectId: number;
  @Input()
  sectionId: number;
  @Input()
  fileExt: string;
  @Input()
  maxFiles: number;
  @Input()
  maxSize: number; // 10MB
  @Output()
  uploadStatus = new EventEmitter();
  img_path = environment.imageUrl+'/assets/img/Taflow/';
  private uploadedUsers: any[];
  private failedProfiles: any[];

  // pager object
  pager: any = {};
  // paged items
  pagedItems: any[];
  uploadSuccess: boolean;
  uploadCount: number;
  failedCount: number;
  allSkilltrack: any;
  allExperiencelevel: any;
  showEditBtn: any;
  empData;
  allCbsChecked: boolean;
  newData: any;
  imageUrl: string = environment.imageUrl;
  constructor(
    private navBarService: NavBarService,
    private bulkUploadFileService: BulkUploadFileService,
    private toastr: ToastsManager,
    private pagerService: PagerService,
    private localStorageService: LocalStorageService,
    private router: Router
  ) {
    this.allCbsChecked = false;
    this.uploadSuccess = false;
    this.maxSize = 10;
    this.maxFiles = 100;
    this.fileExt  = 'xls, xlsm, csv, xltx, xlt, xlsx, doc, docx, pdf, rtf, odt';
    this.dragAreaClass = 'dragarea';
    this.projectId = 0;
    this.sectionId = 0;
    const empData = this.localStorageService.get('userInfo');
    this.empData = empData;
    this.getAllSkillTrackMstr();
    this.allExperiencelevels();
    this.navBarService.setCurrentPage(4);
  }

  ngOnInit() {
    this.navBarService.setCurrentPage(4);
  }
  onFileChange(event) {
    const 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();
    const files = event.dataTransfer.files;
    this.saveFiles(files);
  }
  getAllSkillTrackMstr() {
    this.bulkUploadFileService.allSkilltrackMstrs().subscribe(
      data => {
        this.allSkilltrack = data;
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }

  allExperiencelevels() {
    this.bulkUploadFileService.allExperiencelevels().subscribe(
      data => {
        this.allExperiencelevel = data;
      },
      error => {
        console.log(JSON.stringify(error));
      }
    );
  }
  saveFiles(files) {
    this.errors = []; // Clear error
    // Validate file size and allowed extensions
    if (files.length > 0 && !this.isValidFiles(files)) {
      this.uploadStatus.emit(false);
      return;
    }
    if (files.length > 0) {
      const formData: FormData = new FormData();
      // formData.append('loggedInUser', this.empData.email);
      for (let 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.upload(formData, this.empData.email).subscribe(
        uplResult => {
          this.uploadStatus.emit(true);
          console.log(uplResult);
          this.uploadedUsers = uplResult.requestBeansList;
          this.uploadSuccess = true;
          this.uploadCount = this.uploadedUsers.length;

          this.failedProfiles = uplResult.failedUserList;
          this.failedCount = this.failedProfiles.length;
          this.failedProfileChanges(this.failedProfiles);
        },
        error => {
          // console.log(JSON.stringify(error));
          this.toastr.error(error);
          this.uploadStatus.emit(true);
          this.errors.push(error.ExceptionMessage);
        }
      );
    }
  }

  failedProfileChanges(data) {
    console.log(data);
    if (data) {
      _.forEach(data, (element, i) => {
        this.failedProfiles[i].user.skillDetails = [];
        _.forEach(this.allExperiencelevel.pgExperienceList, (list, j) => {
          if (+element.user.experienceLevel === list.experienceLevelId) {
            this.failedProfiles[i].user.experienceLevel = list.experienceLevel;
          }
        });
        _.forEach(element.user.skillId, (listData, k) => {
          _.forEach(
            this.allSkilltrack.pgSkillTrackDtlsList,
            (skillDetails, l) => {
              if (skillDetails.skillTrackDtlsId === listData) {
                this.failedProfiles[i].user.skillDetails.push(
                  skillDetails.skillTrackDtlsName
                );
              }
            }
          );
        });
      });
    }
  }
  setPage(page: number) {
    if(this.pager.totalPages){
      if (page < 1 || page > this.pager.totalPages) {
        return;
      }
    }
    // get pager object from service
    this.pager = this.pagerService.getPager(this.uploadedUsers.length, page);
    console.log('Pager --- ' + JSON.stringify(this.pager));
    // get current page of items
    this.pagedItems = this.uploadedUsers.slice(
      this.pager.startIndex,
      this.pager.endIndex + 1
    );
  }

  private isValidFiles(files) {
    // Check Number of files
    if (files.length > this.maxFiles) {
      this.errors.push(
        'Error: At a time you can upload only ' + this.maxFiles + ' files'
      );
      return;
    }
    this.isValidFileExtension(files);
    return this.errors.length === 0;
  }

  private isValidFileExtension(files) {
    // Make array of file extensions
    const extensions = this.fileExt.split(',').map(function(x) {
      return x.toLocaleUpperCase().trim();
    });
    for (let i = 0; i < files.length; i++) {
      // Get file extension
      const ext =
        files[i].name
          .toUpperCase()
          .split('.')
          .pop() || files[i].name;
      // Check the extension exists
      const exists = extensions.includes(ext);
      if (!exists) {
        this.errors.push('Error (Extension): ' + files[i].name);
      }
      // Check file size
      this.isValidFileSize(files[i]);
    }
  }

  private isValidFileSize(file) {
    const fileSizeinMB = file.size / (1024 * 1000);
    const size = Math.round(fileSizeinMB * 100) / 100; // convert upto 2 decimal place
    if (size > this.maxSize) {
      this.errors.push(
        'Error (File Size): ' +
          file.name +
          ': exceed file size limit of ' +
          this.maxSize +
          'MB ( ' +
          size +
          'MB )'
      );
    }

  }

  updateCheckedOptions(id, index, e) {
    console.log(id, index, e.target.value);

    if (e.target.checked === true) {
      this.showEditBtn = index;
    } else {
      this.showEditBtn = index + 0.5;
    }
  }

  selAllCkbxs(e) {
    if (e.target.checked === true) {
      this.allCbsChecked = true;
    } else {
      this.allCbsChecked = false;
    }
  }

  editUploadedProfileOfBu(id, index) {
    console.log('Profile to edit', id, index);
  }

  deleteuploadedProfileOfBu(id, index) {
    console.log('Profile to delete', id, index);
  }

  discardBulkUploadConfirm() {
    console.log('discard button clicked');
  }

  submitBulkUploadConfirm() {
    console.log('submit button clicked');
    this.router.navigate(['/ta']);
    this.navBarService.setCurrentPage(0);
  }
}
