import { Component, Input, OnInit } from '@angular/core';
import { NavBarService } from '../ta.service';
import { IMyDrpOptions } from 'mydaterangepicker';
import { AuthService } from '../../services/auth.service';
import { utils, WorkBook, write } from 'xlsx';
// import { saveAs } from 'file-saver';
import { saveAs as importedSaveAs } from 'file-saver';

import { ToastsManager } from 'ng2-toastr';

@Component({
  selector: 'app-ta-reports',
  templateUrl: './ta-reports.component.html',
  styleUrls: ['./ta-reports.component.scss']
})
export class TaReportsComponent implements OnInit {

  reportLevels = []
  udr = false;
  filterFileds = [{ filed: 'Name', checked: true },
  { filed: 'Email', checked: true },
  { filed: 'Phone', checked: true },
  { filed: 'Skill', checked: true },
  { filed: 'Level', checked: true },
  { filed: 'Location', checked: false },
  { filed: 'Job Name', checked: false },
  { filed: 'Score', checked: false },
  { filed: 'Feedback', checked: false }]

  myDateRangePickerOptions: IMyDrpOptions = {
    // other options...
    dateFormat: 'dd.mm.yyyy',
    showClearBtn: true,
    inline: false,
  };
  private model: any = {
    beginDate: { year: 2018, month: 10, day: 9 },
    endDate: { year: 2018, month: 10, day: 19 }
  };
  private feedbackDateModel: any = {
    beginDate: { year: 2018, month: 10, day: 9 },
    endDate: { year: 2018, month: 10, day: 19 }
  };

  private checkedInCandidatesDateModel: any = {
    beginDate: { year: 2018, month: 10, day: 9 },
    endDate: { year: 2018, month: 10, day: 19 }
  };

  private copyModel: any = {
    beginDate: { year: 2018, month: 10, day: 9 },
    endDate: { year: 2018, month: 10, day: 19 }
  };

  userList = [];
  feedbackUserList = [];
  checkedInCandidatesList = [];
  reportTemplateList =  [

    {

      "reportTemplateId": 1,

      "reportCategory": "STANDARD_REPORT",

      "reportTemplateName": "MettlScores",

      "reportTemplatePath": "D:\\Projects\\PlayGround\\Codebase\\playground-reportsvc\\uploads\\Cherry_Landscape_1.jrxml",

      "compiledReportTemplatePath": "D:\\Projects\\PlayGround\\Codebase\\playground-reportsvc\\uploads\\Cherry_Landscape_1.jasper",

      "compilationStatus": true,

      "validationStatus": false,

      "downloadURI": "http://localhost:8080/reportsvc/v1/report/Cherry_Landscape_1.jrxml",

      "createdOn": "2018-11-13T06:46:42.000+0000",

      "modifiedOn": "2018-11-13T06:46:42.000+0000",

      "createdBy": null,

      "updatedBy": null

    },
    {

      "reportTemplateId": 1,

      "reportCategory": "STANDARD_REPORT",

      "reportTemplateName": "MettlScores",

      "reportTemplatePath": "D:\\Projects\\PlayGround\\Codebase\\playground-reportsvc\\uploads\\Cherry_Landscape_1.jrxml",

      "compiledReportTemplatePath": "D:\\Projects\\PlayGround\\Codebase\\playground-reportsvc\\uploads\\Cherry_Landscape_1.jasper",

      "compilationStatus": true,

      "validationStatus": false,

      "downloadURI": "http://localhost:8080/reportsvc/v1/report/Cherry_Landscape_1.jrxml",

      "createdOn": "2018-11-13T06:46:42.000+0000",

      "modifiedOn": "2018-11-13T06:46:42.000+0000",

      "createdBy": null,

      "updatedBy": null

    }]

  noRecord = true;
  nofeedbackRecord = true;
  noCheckedInRecored = true;

  @Input() level = '';
  @Input() status = '';
  @Input() location = '';
  @Input() jobName = '';

  feedLocation = [];
  feedPosition = [];
  checkInLocation = [];
  checkInPosition = [];
  jobAssessments = [];
  locations = [];
  expLevels = [];

  data = [];

  allStatus = [

    { name: 'Mettl Initiate', value: 'METTL_INITIATED' },
    { name: 'Mettl Inprogress', value: 'METTL_IN_PROGRESS' },
    { name: 'Mettl Review', value: 'METTL_REVIEW' },
    { name: 'Mettl Cleared', value: 'METTL_CLEARED' },
    { name: 'Mettl Failed', value: 'METTL_FAILED' },
    { name: 'Coding Challenge Ready', value: 'CODING_CHALLENGE_READY' },
    { name: 'Coding Challenge Initiated', value: 'CODING_CHALLENGE_INITIATED' },
    { name: 'Coding Challenge Started', value: 'CODING_CHALLENGE_STARTED' },
    { name: 'Coding Challenge Completed', value: 'CODING_CHALLENGE_COMPLETED' },
    { name: 'Coding Challenge Cleared', value: 'CODING_CHALLENGE_CLEARED' },
    { name: 'Coding Challenge Rejected', value: 'CODING_CHALLENGE_REJECTED' },
  ];

  reqJson = {
    'filter': {
      'jobRequirements': [],
      'eventName': [],
      'locations': [],
      'onboardDates': [],
      'status': []
    }
  };

  feedbackJson = {
    'fromDate': '',
    'location': this.feedLocation,
    'position': this.feedPosition,
    'toDate': ''
  };

  checkedInCandidatesJson = {
    'fromDate': '',
    'location': this.checkInLocation,
    'position': this.checkInPosition,
    'toDate': ''
  };

  allCandidatesBlock = true;
  checkInCandidatesBlock: boolean;
  feedbackBlock: boolean;
  reportTemplate: boolean;

  selectedFile: any;

  constructor(private navBarService: NavBarService,
    private AuthService: AuthService,
    private toaster: ToastsManager, ) {


    const Today = new Date();
    console.log(Today, 'todayyyyyyyyyyyyy');
    const day = Today.getDate();
    const monthIndex = Today.getMonth();
    const currentmonthIndex = monthIndex + 1;
    const year = Today.getFullYear();

    this.model = {
      endDate: { year: year, month: currentmonthIndex, day: day },
      beginDate: { year: year, month: monthIndex, day: day }
    };

    this.feedbackDateModel = {
      endDate: { year: year, month: currentmonthIndex, day: day },
      beginDate: { year: year, month: monthIndex, day: day }
    };

    this.checkedInCandidatesDateModel = {
      endDate: { year: year, month: currentmonthIndex, day: day },
      beginDate: { year: year, month: monthIndex, day: day }
    };
    this.copyModel = {
      endDate: { year: year, month: currentmonthIndex, day: day },
      beginDate: { year: year, month: monthIndex, day: day }
    };

    this.myDateRangePickerOptions = {
      disableSince: { year: year, month: currentmonthIndex, day: day + 1 }
    };

    this.getAllFilterData();

    this.navBarService.setCurrentPage(6);
  }

  getAllFilterData() {
    this.AuthService.getLocations().then(res => {
      const skill = res;
      this.locations = skill.pgLocationList;
      // console.log(this.locations, 'locations');
    }).catch(err => {
      console.log(err);
    });

    this.AuthService.getAllExperienceLevel().then(res => {
      const exp = res;
      this.expLevels = exp.pgExperienceList;
      // console.log(this.expLevels, 'getAllExperience');
    }).catch(err => {
      console.log(err);
    });

    this.AuthService.getAllAssessment().then(res => {
      const assess = res;
      this.jobAssessments = assess;
      // console.log(this.jobAssessments, 'assess');
    }).catch(err => {
      console.log(err);
    });

    this.reportLevels = [
      { name: 'Primary challenge', value: 'Candidate Mettl' },
      { name: 'Coding Challenge', value: 'Candidate Coding Challenge' },
    ]
  }

  ngOnInit() {
    this.navBarService.setCurrentPage(6);
  }

  selectFilter(id) {
    if (id === 3) {
      this.udr = true;
    } else {
      this.udr = false;
    }
  }

  locationFilter(id) {
    this.reqJson.filter.locations = id;
  }

  feedbackLocationfilter(id) {
    this.feedbackJson.location = id;
  }

  checkedInCandidatesLocationfilter(id) {
    this.checkedInCandidatesJson.location = id;
  }

  jobFilter(id) {
    this.reqJson.filter.jobRequirements = id;
  }

  feedbackJobfilter(id) {
    this.feedbackJson.position = id;
  }

  checkedInJobfilter(id) {
    this.checkedInCandidatesJson.position = id;
  }

  statusFilter(id) {
    this.reqJson.filter.status = id;
  }
  levelFilter(id) {
    this.reqJson.filter.eventName = id;
  }

  getDateFormat(e, id) {
    if (id === 1) {
      if (e.beginJsDate && e.endJsDate) {
        this.reqJson.filter.onboardDates = [e.beginDate.year + '-' + e.beginDate.month + '-' + e.beginDate.day + '/' + e.endDate.year + '-' + e.endDate.month + '-' + e.endDate.day];
      }
    } else if (id === 2) {
      if (e.beginJsDate && e.endJsDate) {
        this.checkedInCandidatesJson.fromDate = e.beginDate.year + '-' + e.beginDate.month + '-' + e.beginDate.day;
        this.checkedInCandidatesJson.toDate = e.endDate.year + '-' + e.endDate.month + '-' + e.endDate.day;
      }
    } else if (id === 3) {
      if (e.beginJsDate && e.endJsDate) {
        this.feedbackJson.fromDate = e.beginDate.year + '-' + e.beginDate.month + '-' + e.beginDate.day;
        this.feedbackJson.toDate = e.endDate.year + '-' + e.endDate.month + '-' + e.endDate.day;
      }
    }

  }

  availableFilter(e, index) {
    // console.log(e, index);
    if (e.target.checked) {
      this.filterFileds[index].checked = e.target.checked;
    } else {
      this.filterFileds[index].checked = e.target.checked;
    }
  }


  clearFilter() {
    this.userList = [];
    this.noRecord = true;
    this.jobName = undefined;
    this.level = undefined;
    this.location = undefined;
    this.status = undefined;
    this.model = this.copyModel;
    this.reqJson = {
      'filter': {
        'jobRequirements': [],
        'eventName': [],
        'locations': [],
        'onboardDates': [],
        'status': []
      }
    };
  }

  loadData() {
    if(this.reqJson.filter.onboardDates.length == 0) {
      console.log('date not found');
      this.reqJson.filter.onboardDates = [this.model.beginDate.year + '-' + this.model.beginDate.month + '-' + this.model.beginDate.day + '/' + this.model.endDate.year + '-' + this.model.endDate.month + '-' + this.model.endDate.day]
    }
    if (this.reqJson.filter.jobRequirements.length === 0) {
      this.toaster.error('Please select Job requirement name');
    } else if (this.reqJson.filter.eventName.length === 0) {
      this.toaster.error('Please select levels');
    } else {
      console.log(this.reqJson);
      this.AuthService.getCandidateReport(this.reqJson).then(res => {
        console.log(res, 'load-Candidate-Data');
        this.userList = res.webReport;
        this.noRecord = false;
      }).catch(err => {
        console.log(err);
      });
    }
  }

  getLw(str) {
    return str.toLowerCase()
  }

  exports() {
    this.genericExportsMethod(this.userList, 'exported.xlsx' )
  }

  genericExportsMethod(userDataForExcel,fileName) {
    const ws_name = 'SomeSheet';
    const wb: WorkBook = { SheetNames: [], Sheets: {} };
    const ws: any = utils.json_to_sheet(userDataForExcel);
    wb.SheetNames.push(ws_name);
    wb.Sheets[ws_name] = ws;
    const wbout = write(wb, {
      bookType: 'xlsx', bookSST: true, type:
        'binary'
    });
    function s2ab(s) {
      const buf = new ArrayBuffer(s.length);
      const view = new Uint8Array(buf);
      for (let i = 0; i !== s.length; ++i) {
        view[i] = s.charCodeAt(i) & 0xFF;
      };
      return buf;
    }
    importedSaveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), fileName);
  }
  loadFeedbackData() {
    if(this.feedbackJson.fromDate == '' || this.feedbackJson.toDate == '') {
      this.feedbackJson.fromDate = this.feedbackDateModel.beginDate.year + '-' + this.feedbackDateModel.beginDate.month + '-' + this.feedbackDateModel.beginDate.day;
      this.feedbackJson.toDate = this.feedbackDateModel.endDate.year + '-' + this.feedbackDateModel.endDate.month + '-' + this.feedbackDateModel.endDate.day;
    }
    if (this.feedPosition.length === 0) {
      this.toaster.error('Please select Position');
    } else {
      this.AuthService.getFeedbackReport(this.feedbackJson).then(res => {
        // console.log(res, 'load-Candidate-Data');
        this.feedbackUserList = res;
        this.nofeedbackRecord = false;
      }).catch(err => {
        console.log(err);
      });
    }
  }

  loadcheckedInCandidatesData() {
    if(this.checkedInCandidatesJson.fromDate == '' || this.checkedInCandidatesJson.toDate == '' ) {
      console.log('no date found');
      this.checkedInCandidatesJson.fromDate = this.checkedInCandidatesDateModel.beginDate.year + '-' + this.checkedInCandidatesDateModel.beginDate.month + '-' + this.checkedInCandidatesDateModel.beginDate.day;
      this.checkedInCandidatesJson.toDate = this.checkedInCandidatesDateModel.endDate.year + '-' + this.checkedInCandidatesDateModel.endDate.month + '-' + this.checkedInCandidatesDateModel.endDate.day;
    }
    if (this.checkInPosition.length === 0) {
      this.toaster.error('Please select Position');
    } else {
      this.AuthService.getCandidateCheckedInReportData(this.checkedInCandidatesJson).then(res => {
        // console.log(res, 'load-Candidate-Data');
        this.checkedInCandidatesList = res;
        this.noCheckedInRecored = false;
      }).catch(err => {
        console.log(err);
      });
    }
  }

  viewchange(view) {
    if (view === 'allCandidatesBlock') {
      this.allCandidatesBlock = true;
      this.checkInCandidatesBlock = false;
      this.feedbackBlock = false;
      this.reportTemplate = false;
      this.clearFeedbackData();
      this.clearChekedInData();
    } else if (view === 'checkInCandidatesBlock') {
      this.allCandidatesBlock = false;
      this.checkInCandidatesBlock = true;
      this.feedbackBlock = false;
      this.reportTemplate = false;
      this.clearFeedbackData();
      this.clearFilter();
    } else if (view === 'feedbackBlock') {
      this.allCandidatesBlock = false;
      this.checkInCandidatesBlock = false;
      this.feedbackBlock = true;
      this.reportTemplate = false;
      this.clearChekedInData();
      this.clearFilter();
    } else if (view === 'reportTemplate') {
      this.allCandidatesBlock = false;
      this.checkInCandidatesBlock = false;
      this.feedbackBlock = false;
      this.reportTemplate = true;
      this.clearChekedInData();
      this.clearFilter();
    }
  }

  clearFeedbackData() {
    this.feedbackUserList = [];
    this.nofeedbackRecord = true;
    this.feedLocation = undefined;
    this.feedPosition = undefined;
    this.feedbackDateModel = this.copyModel;
    this.feedbackJson = {
      'fromDate': '',
      'location': this.feedLocation,
      'position': this.feedPosition,
      'toDate': ''
    };
  }

  clearChekedInData() {
    this.checkedInCandidatesList = [];
    this.noCheckedInRecored = true;
    this.checkInLocation = undefined;
    this.checkInPosition = undefined;
    this.checkedInCandidatesDateModel = this.copyModel;
    this.checkedInCandidatesJson = {
      'fromDate': '',
      'location': this.checkInLocation,
      'position': this.checkInPosition,
      'toDate': ''
    };
  }

  exportFeedbackData() {
    this.AuthService.getFeedbackReportdowmloading(this.feedbackJson).then((res: any) => {
      // console.log('Res for docs download' + res);
         console.log(res);
      const blob = new Blob([res._body], { type: 'application/octet-stream' });
      // saveAs(blob, 'feebackUserList.xlsx');
    //  importedSaveAs(blob, 'feebackUserList.xls');
    }).catch(err => {
      console.log(err);
    });

  }

  exportCandidateCheckedInReport() {
    this.AuthService.getCandidateCheckedInReportDownloading(this.checkedInCandidatesJson).then(res => {
      console.log(res);
      const blob = new Blob([res], { type: 'application/vnd.ms-excel' });
     // importedSaveAs(blob, 'CandidateCheckedInReport.xls');
    }).catch(err => {
      console.log(err);
    });
  }

  /*UPLOAD TEMPLATE FUNCTION START HERE*/


  onFileChange(event) {
    const files = event.target.files;
    console.log(files);
    if(files[0].type !== 'text/xml'){
      this.toaster.error('Invalid file format')
    } else {
      this.selectedFile = files;
    }


  }

  uploadTemplate(){

  }




}
