import { Component, OnInit, ViewChild } from "@angular/core";
import { Location } from "@angular/common";
import { TranslatorService } from "src/app/hmg-common/services/translator/translator.service";
import { CommonService } from "src/app/hmg-common/services/common/common.service";
import { AuthenticationService } from "src/app/hmg-common/services/authentication/authentication.service";
import { MenuResponse } from "src/app/hmg-common/services/menu/models/menu-response";
import { MyTeamService } from "../service/my-team.service";
import { ModalController, IonInfiniteScroll } from "@ionic/angular";
import { DetailsComponent } from '../details/details.component';
@Component({
  selector: "app-home",
  templateUrl: "./home.component.html",
  styleUrls: ["./home.component.scss"]
})
export class HomeComponent implements OnInit {
  @ViewChild(IonInfiniteScroll) infiniteScroll: IonInfiniteScroll;

  pageNum: number = 1;
  pageLimit: number = 50;
  empSubordinate: any;
  employee: any;
  public headerTitle: string = "";
  IsReachEnd: boolean = false;
  searchKey: any;
  public isSearch: boolean = false;
  public searchKeySelect: any;
  infiniteRequest: any;
  selMenu: any;
  selEmpNo: any;
  constructor(
    public ts: TranslatorService,
    public authService: AuthenticationService,
    public common: CommonService,
    public myTeamService: MyTeamService,
    public modalController: ModalController,
    private location: Location
  ) {}

  ngOnInit() {
    this.common.sharedService.setSharedData( [], DetailsComponent.opendEmployeesARR);
    this.setIntitial();
  }
  goback() {
    this.location.back();
  }
  getData() {}
  setIntitial() {
    this.selMenu = this.common.sharedService.getSharedData(
      MenuResponse.SHARED_DATA,
      false
    );
    this.headerTitle = this.selMenu.List_Menu.MENU_NAME;
    this.selEmpNo = this.selMenu.userid;
    this.isSearch = this.selMenu.search ? this.selMenu.search : this.isSearch;
    // this.isSearch=this.navParams.get("isSearch")?this.navParams.get("isSearch") : false;
    if (!this.isSearch) this.getEmpSubordinate();
  }
  getEmpSubordinate() {
    console.log("getEmpSubordinate my team home");
    this.pageNum = 1;
    this.IsReachEnd = false;
    let searchEmpNum = "";
    let searchEmpName = "";
    let searchEmpEmail = "";
    if (this.searchKey) {
      switch (this.searchKeySelect) {
        case "1": {
          searchEmpName = this.searchKey;
          searchEmpNum = "";
          searchEmpEmail = "";

          break;
        }
        case "2": {
          searchEmpNum = this.searchKey;
          searchEmpName = "";
          searchEmpEmail = "";
          break;
        }
        case "3": {
          searchEmpEmail = this.searchKey;
          searchEmpNum = "";
          searchEmpName = "";
          break;
        }
        default: {
          searchEmpNum = "";
          searchEmpName = "";
          searchEmpEmail = "";
          break;
        }
      }
    } else {
      searchEmpNum = "";
      searchEmpName = "";
      searchEmpEmail = "";
    }
    if (this.isSearch) {
      this.selEmpNo = null;
    }

    const body = {
      P_SELECTED_EMPLOYEE_NUMBER: this.selEmpNo,
      P_SEARCH_EMPLOYEE_NUMBER: searchEmpNum,
      P_SEARCH_EMPLOYEE_DISPLAY_NAME: searchEmpName,
      P_SEARCH_EMAIL_ADDRESS: searchEmpEmail,
      P_PAGE_NUM: this.pageNum,
      P_PAGE_LIMIT: this.pageLimit
    };
    this.infiniteRequest = body;
    this.myTeamService
      .getEmployeeSubordinates(body)
      .subscribe((result: any) => {
        this.handleEmpResult(result);
      });
  }

  handleEmpResult(result) {
    if (this.common.validResponse(result)) {
      if (this.common.hasData(result.GetEmployeeSubordinatesList)) {

        this.empSubordinate = result.GetEmployeeSubordinatesList;
        this.infiniteRequest.P_PAGE_NUM++;
        const lastItemIndex = this.empSubordinate.length - 1;
        if (result.GetEmployeeSubordinatesList[lastItemIndex]) {
          const lastitem = result.GetEmployeeSubordinatesList[lastItemIndex];
          if (lastitem.NO_OF_ROWS == lastitem.ROW_NUM) {
            this.IsReachEnd = true;
          } else {
            this.IsReachEnd = false;
          }
        }
      } else {
        this.empSubordinate = [];
      }
    }
  }







  doInfinite1(infiniteScroll) {
    console.log("test");
    if (!this.IsReachEnd && this.infiniteRequest) {
      console.log("not ReachEnd");

      this.infiniteRequest.P_PAGE_NUM = this.pageNum;
      this.myTeamService
        .getEmployeeSubordinates(this.infiniteRequest)
        .subscribe(
          (result: any) => {
            if (this.common.validResponse(result)) {
              this.pageNum++;
              if (this.common.hasData(result.GetEmployeeSubordinatesList)) {
                result.GetEmployeeSubordinatesList.forEach(vr => {
                  if (vr.ROW_NUM == vr.NO_OF_ROWS) {
                    this.IsReachEnd = true;
                  } else {
                    this.IsReachEnd = false;
                  }
                  this.empSubordinate.push(vr);
                  // this.pro.GetVacationRulesList.push(vr);
                });
              } else {
                this.IsReachEnd = true;
              }
            }
            //this.P_PAGE_NUM++;
            if (infiniteScroll) {
              infiniteScroll.complete();
            }
            // console.log(resFlag);
          },
          Error => console.log(Error),
          () => infiniteScroll.complete()
        );
    } else {
      if (infiniteScroll) {
        infiniteScroll.complete();
      }
    }
  }


  doInfinite(infiniteScroll) {
    //this.pageNum= this.pageNum + 1;
   console.log("test doInfinite");
    if (!this.IsReachEnd) {
      console.log("test doInfinite not ReachEnd");

      this.myTeamService
      .getEmployeeSubordinates(this.infiniteRequest).subscribe(
        (result: any) => {
          if (this.common.validResponse(result)) {
            this.infiniteRequest.P_PAGE_NUM++;
            if (this.common.hasData(result.GetEmployeeSubordinatesList)) {
              result.GetEmployeeSubordinatesList.forEach(element => {
                if (element.ROW_NUM == element.NO_OF_ROWS) {
                  this.IsReachEnd = true;
                } else {
                  this.IsReachEnd = false;
                }
                this.empSubordinate.push(element);
              });
            } // if list length >0
            else {
              this.IsReachEnd = true;
            }
          } // if response == 1
          //this.pageNum++;
          this.infiniteScroll.complete();
        }
      );
    } else {
      if (this.infiniteScroll)
       this.infiniteScroll.complete();
    }
  } //end infiniteScroll





  getDetails(index) {
    this.common.sharedService.setSharedData(
      this.empSubordinate[index],
      MyTeamService.EMPLOYEE_SHARED_DATA
    );

    this.common.sharedService.setSharedData(
      this.selMenu,
      MenuResponse.SHARED_DATA
    );
    this.close().then(() => {
      this.common.openMyTeamDetails();
    });

    //this.modalController.dismiss();
    //this.navCtrl.push("MyTeamPage",{employee:this.empSubordinate[index]});
  }
  public async close() {
    const modal = await this.modalController.getTop();
    if (modal) {
      modal.dismiss();
    }
  }
  toggleSearch() {
    this.isSearch = !this.isSearch;
  }
  goToSubordinate() {
    //this.navCtrl.push("MySubordinatePage",{isSearch:true});
    //this.getEmpSubordinate();
    this.presentModal();
  }
  async presentModal() {
    const modal = await this.modalController.create({
      component: HomeComponent,
      keyboardClose: true,
      animated: false,
      componentProps: { isSearch: true }
    });
    modal.cssClass="full-modal";
    let dismissed = modal.onDidDismiss();
    dismissed.then(() => {
      this.isSearch = false;
    });
    return await modal.present();
  }
  dismiss() {
    this.modalController.dismiss({
      dismissed: true
    });
  }
  
}
