import { AfterViewInit, Component, HostListener, Input } from '@angular/core';
import { LoginPopupComponent } from '@app_core/components/login/login-popup/login-popup.component';
import { EN_EntityBeforeSaveCallBackResults } from '@app_core/consts';
import { AuthorizeService } from '@app_core/services/authorize.service';
import { PageLoadingService } from '@app_core/services/pageloading.service';
import { Employee } from '@app_models/employee';
import { EmployeeDataService } from '@app_modules/employee/employee-data.service';
import { AppBaseEntityWrapper } from '@app_services/app.baseentity.wrapper';

@Component({
  selector: 'app-employee-detail',
  templateUrl: './employee-detail.component.html',
  styleUrls: ['./employee-detail.component.scss'],
})
export class EmployeeDetailComponent implements AfterViewInit {
  @Input() public employeeDetails: AppBaseEntityWrapper<Employee>;

  constructor(
    public employeeDataService: EmployeeDataService,
    public authorizeService: AuthorizeService,
    private pageLoadingService: PageLoadingService,
  ) {
  }

  public get focusedItem(): Employee {
    return this.employeeDetails.entity;
  }

  ngAfterViewInit(): void {
    this.employeeDetails.beforeNewCallBack = this.newEmployeeInit.bind(this);
    this.employeeDetails.beforeSaveCallBack = this.beforeSaveEmployee.bind(this);
  }

  newEmployeeInit(employee: Employee) {
    /*    employee.createdOn = new Date();
        employee.createdBy = this.authorizeService.user.userCode;
        employee.changedOn = employee.createdOn;
        employee.changedBy = employee.createdBy;*/
  }

  async beforeSaveEmployee(employee: Employee): Promise<EN_EntityBeforeSaveCallBackResults> {
    this.employeeDataService.employee2AttributeList.match2array(employee, 'employeeId', 'arAttributeIdList', 'employeeAttributeId');
    return EN_EntityBeforeSaveCallBackResults.Ok_Continue;
  }


  public save = () => { //because of calling as callback of cancel
    this.pageLoadingService.startSpinner();
    this.employeeDetails.save((employee: Employee) => this.afterSave(employee), null, () => this.pageLoadingService.hideSpinner());
  }

  afterSave(employee: Employee) {
    // this.employeeDetails.loadDetails(this.catalogDataService.employeeCategoryList);

  }

  public cancel = () => {
    // this.setCurrentMaster4Subemployee = null;
    this.employeeDetails.cancelWithSave(this.save);
  }

  public add(){
    this.employeeDetails.new();
    this.employeeDetails.entity.isActive = true;
  }
  @HostListener('window:keydown', ['$event'])
  keyboardInput(event: any) {
    return LoginPopupComponent.LOGIN_IS_SHOWN || this.employeeDetails.shortcutsHandler(event, this.save, this.cancel);
  }

}
