import { Component, OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { ReplacementServiceRequest } from 'src/app/vacation-rule/model/replacement-Service.request';
import { VacationRuleServiceService } from 'src/app/vacation-rule/service/vacation-rule-service.service';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { WorklistService } from '../service/worklist.service';


@Component({
  selector: 'app-work-list-replacement-itg',
  templateUrl: './work-list-replacement-itg.component.html',
  styleUrls: ['./work-list-replacement-itg.component.scss'],
})
export class WorkListReplacementItgComponent implements OnInit {
  messageSuccess = false;
  P_SEARCH_USER_NAME: string = "";
  P_SEARCH_EMPLOYEE_DISPLAY_NAME: string = "";
  P_SEARCH_EMAIL_ADDRESS: string = "";
  P_PAGE_NUM: number = 1;
  P_PAGE_LIMIT: number = 50;
  ReplacementList: any = [];
  IsReachEnd: boolean = false;
  selEmp: string = null;
  callback: any;
  searchKey: any = "";
  searchKeySelect: string = "1";
  replacmentRequest: any = "";
  isAbs: boolean = false;
  isSave: boolean = false;
  isSelect: boolean = false;
  typingTimer: any;
  userSelected: any;
  active: any;
  isAnswer: boolean = false;
  favoriteUserList = [];
  userNote: any;
  isFilter = true;
  relatedList = [];
  public direction = '';
  arr = [];
  delegtedEmp;
  constructor(public vacationRuleService: VacationRuleServiceService,
    public ts: TranslatorService,
    public cs: CommonService,
    public worklistService: WorklistService,
    public modalController: ModalController) {
    this.direction = TranslatorService.getCurrentDirection();
    console.log(this.direction);
  }

  // async ionViewWillEnter() {
  //   await this.getFavruite();
  // }

  ngOnInit() {
    this.delegtedEmp = this.cs.sharedService.getSharedData('selectedEmpInfo', true);
    if (this.delegtedEmp === undefined) {
      if (!this.relatedList || this.relatedList.length === 0 || this.relatedList === undefined) {
        this.arr = this.cs.sharedService.getSharedData('workflow-user', false);
        var lookupObject = {};
        for (var i in this.arr) {
          lookupObject[this.arr[i]['Name']] = this.arr[i];
        }
        for (i in lookupObject) {
          this.relatedList.push(lookupObject[i]);
        }
      }
    } else {
      this.select(this.delegtedEmp, 1);
    }
  }

  SearchReplacementList() {
    this.ReplacementList = [];
    this.IsReachEnd = false;
    this.P_PAGE_NUM = 1;
    if (this.searchKey) {
      switch (this.searchKeySelect) {
        case '1': {

          this.P_SEARCH_EMPLOYEE_DISPLAY_NAME = this.searchKey;
          this.P_SEARCH_USER_NAME = "";
          this.P_SEARCH_EMAIL_ADDRESS = "";

          break;
        }
        case '2': {
          this.P_SEARCH_USER_NAME = this.searchKey;
          this.P_SEARCH_EMPLOYEE_DISPLAY_NAME = "";
          this.P_SEARCH_EMAIL_ADDRESS = "";
          break;
        }
        case '3': {
          this.P_SEARCH_EMAIL_ADDRESS = this.searchKey;
          this.P_SEARCH_USER_NAME = "";
          this.P_SEARCH_EMPLOYEE_DISPLAY_NAME = "";
          break;
        }
        default: {
          this.P_SEARCH_USER_NAME = "";
          this.P_SEARCH_EMPLOYEE_DISPLAY_NAME = "";
          this.P_SEARCH_EMAIL_ADDRESS = "";
          break;
        }
      }
    } else {
      this.P_SEARCH_USER_NAME = "";
      this.P_SEARCH_EMPLOYEE_DISPLAY_NAME = "";
      this.P_SEARCH_EMAIL_ADDRESS = "";
    }

    const request = new ReplacementServiceRequest();
    request.P_SEARCH_USER_NAME = this.P_SEARCH_USER_NAME;
    request.P_SEARCH_EMPLOYEE_DISPLAY_NAME = this.P_SEARCH_EMPLOYEE_DISPLAY_NAME;
    request.P_SEARCH_EMAIL_ADDRESS = this.P_SEARCH_EMAIL_ADDRESS;
    request.P_PAGE_NUM = this.P_PAGE_NUM;
    request.P_PAGE_LIMIT = this.P_PAGE_LIMIT;
    request.P_SELECTED_EMPLOYEE_NUMBER = this.selEmp;

    this.vacationRuleService.getReplacementList(request).
      subscribe((result: any) => {
        this.handleReplacment(result);
      });
  }

  handleReplacment(result) {
    if (this.cs.validResponse(result)) {
      if (this.cs.hasData(result.ReplacementList)) {
        this.ReplacementList = result.ReplacementList;
        this.P_PAGE_NUM++;
        let lastItemIndex = this.ReplacementList.length - 1;
        if (result.ReplacementList[lastItemIndex]) {
          let lastitem = result.ReplacementList[lastItemIndex];
          if (lastitem.NO_OF_ROWS == lastitem.ROW_NUM) {
            this.IsReachEnd = true;
          } else {
            this.IsReachEnd = false;
          }
        }
      }
    }
  }

  // doInfinite(infiniteScroll) {

  // }

  closePage() {
    console.log(this.selEmp);
    this.isSave = true;
    let data: any = null;
    if (this.isSave == true) {
      if (this.selEmp) {
        data = this.selEmp;
        this.messageSuccess = true;
      } else {
        data = null;
      }
      if (typeof this.callback == 'function') {
        this.callback(data);
      }

      this.modalController.dismiss({
        'dismissed': true,
        empData: data,
        comments: this.userNote
      });
    }
  }

  closeFunction() {
    this.modalController.dismiss({
      'dismissed': true,
      // comments: this.userNote
    });
  }

  onChangeSelect(select) {
    let selectValue = select.detail.value;
    this.searchKey = '';
    if (selectValue == "1") {
      this.listOfRealted = this.relatedList;
      console.log(this.relatedList);
      this.isSelect = true;
      this.isFilter = true;
      this.ReplacementList = [];
    } else if (selectValue == "4") {
      this.listOfFav = this.favoriteUserList;
      this.isFilter = true;
      this.ReplacementList = [];
      if(this.favoriteUserList.length === 0 || this.favoriteUserList === undefined){
        this.getFavruite();
      }
    } else if (selectValue === '2' || selectValue === '3' || selectValue === '5') {
      this.isSelect = true;
      this.isFilter = false;
    }
    else {
      this.isSelect = false;

    }
  }
  getPlaceHolder() {
    return this.searchKeySelect == '1' ? this.ts.trPK('replacementRoll', 'searchbyname') : this.searchKeySelect == '2' ? this.ts.trPK('replacementRoll', 'searchbyusername') : this.ts.trPK('replacementRoll', 'searchbyemail');
  }
  onChangeInput() {
    this.ReplacementList = [];
    clearTimeout(this.typingTimer);
    this.typingTimer = setTimeout(() => {
      if (this.searchKey.length > 2) {
        this.SearchReplacementList();
      }
    }, 3000);
  }
  select(selectEmp, index) {
    this.selEmp = selectEmp
    this.userSelected = true;
    this.active = index;
    this.searchKey = selectEmp.EMPLOYEE_DISPLAY_NAME ? selectEmp.EMPLOYEE_DISPLAY_NAME : selectEmp.Name;
    //this.closePage();
  }


  setFavorite(selEmp) {
    selEmp.EMPLOYEE_DISPLAY_NAME = selEmp.EMPLOYEE_DISPLAY_NAME ? selEmp.EMPLOYEE_DISPLAY_NAME : selEmp.NAME;
    selEmp.EMPLOYEE_IMAGE = selEmp.EMPLOYEE_IMAGE ? selEmp.EMPLOYEE_IMAGE : '';
    selEmp.EMAIL_ADDRESS = selEmp.EMAIL_ADDRESS ? selEmp.EMAIL_ADDRESS : '';
    var confirmBoxhtml = `<div>
    <h4>Do you want to add ` + selEmp.EMPLOYEE_DISPLAY_NAME + ` in your favorite list </h4>
    <br/>
    <br/>
    <div class="fav-profileImageDiv"><ion-row>`;
    if (selEmp.EMPLOYEE_IMAGE)
      confirmBoxhtml += '<div class="img-box"><img class="empImgeRep" src="data:image/png;base64,' + selEmp.EMPLOYEE_IMAGE + '"></div>';
    if (!selEmp.EMPLOYEE_IMAGE)
      confirmBoxhtml += '<div class="img-box"><img class="empImgeRep" src="../assets/imgs/profile.png"></div>';

    confirmBoxhtml += ` <div class="name-box"><ion-label class="fav-employee-details">

    <span>` + selEmp.EMPLOYEE_DISPLAY_NAME + `</span>
    
   </ion-label>
  
   </div></ion-row> </div>
   </div>`
    let userIndex = this.favoriteUserList.findIndex(x => x['USER_NAME'] == selEmp.USER_NAME)
    if (userIndex == -1)
      this.cs.presentConfirmDialog(
        confirmBoxhtml
        , () => {
          var request =
            [{ "USER_NAME": selEmp['USER_NAME'], "EMPLOYEE_DISPLAY_NAME": selEmp['EMPLOYEE_DISPLAY_NAME'], "EMAIL_ADDRESS": selEmp.EMAIL_ADDRESS, "EMPLOYEE_IMAGE": selEmp.EMPLOYEE_IMAGE, "IsFavorite": true }];

          this.saveUserFavruiteList(request);
        }, () => {

        })

    // if (selectValue == "1" || selectValue == "2" || selectValue == "3") {
    //   this.isSelect = true;
    // }
    // else {
    //   this.isSelect = false;



    // }
  }
  saveUserFavruiteList(request) {
    this.worklistService.saveFavoriteList(request, () => {
    }).subscribe((result) => {
      if (this.cs.validResponse(result)) {
        this.cs.toastPK("replacementRoll", "favorite-saved");

      }
    })
  }
  getFavruite() {
    this.cs.startLoading();
    this.worklistService.getFavorite({}, () => {

    }).subscribe((result) => {
      if (this.cs.validResponse(result)) {
        this.cs.stopLoading();
        this.favoriteUserList = result['Mohemm_GetFavoriteReplacementsList'];
        console.log(this.favoriteUserList);
      }
    })
  }

  listOfRealted = [];
  listOfFav = []

  filterList(event) {
    const val = event.target.value;
    if (this.searchKeySelect === '1') {
      if (val === '') {
        this.relatedList = this.listOfRealted;
      } else {
        this.relatedList = this.listOfRealted.filter((item) => {
          return (item.Name.toLowerCase().indexOf(val.toLowerCase()) > -1);
        });
      }
    } else if (this.searchKeySelect === '4') {
      if (val === '') {
        this.favoriteUserList = this.listOfFav;
      } else {
        this.favoriteUserList = this.listOfFav.filter((item) => {
          return (item.EMPLOYEE_DISPLAY_NAME.toLowerCase().indexOf(val.toLowerCase()) > -1);
        });
      }
    } else {
      return;
    }
  }
  isfavEmp(emp) {
    let isEmp = this.favoriteUserList.find(elm => elm.USER_NAME === emp.EmployeeID);
    return isEmp;
  }

  saveBtnDisabled() {
    if (!this.userNote || this.userNote === '')
      return true;
    else { return false; }
  }
}
