import { Component, Injector, ViewChild, ViewEncapsulation } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { TimeSheetServiceProxy, TimeSheetListDto } from '@shared/service-proxies/service-proxies';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { CreateOrEditTimeSheetModalComponent } from './create-or-edit-timesheet.component';

@Component({
    templateUrl: './timesheet.component.html',
    animations: [appModuleAnimation()],
    encapsulation: ViewEncapsulation.None
})

export class TimeSheetComponent extends AppComponentBase {

   @ViewChild('createOrEditTimeSheetModal', {static: false}) createOrEditTimeSheetModal: CreateOrEditTimeSheetModalComponent;
   @ViewChild('dataTable', {static: true}) dataTable: Table;
   @ViewChild('paginator', {static: true}) paginator: Paginator;

   filters: {
        id: number;
        driver: string;
        
    } = <any>{};

   constructor(
      injector: Injector,
      private _timeSheetServiceProxy: TimeSheetServiceProxy
   ) {
      super(injector);  
   }


   create() {
      this.createOrEditTimeSheetModal.show();
   }

   update(id: number): void {
      this.createOrEditTimeSheetModal.show(id);
   }

   delete(timesheet: TimeSheetListDto): void {

      this.message.confirm(
         this.l('TimeSheetDeleteWarningMessage'),
         this.l('AreYouSure'),
         (isConfirmed)=> {
             if(isConfirmed) {
                 this._timeSheetServiceProxy
                     .deleteTimeSheet(timesheet.id)
                     .subscribe(()=> {
                         this.reloadPage();
                         this.notify.success(this.l('SuccessfullyDeleted'));
                     });
             }
         }
     )
   }

   reloadPage(): void {
      this.paginator.changePage(this.paginator.getPage());
   }

   
   getData(event?: LazyLoadEvent) {

      this.spinnerService.show();

      if (this.primengTableHelper.shouldResetPaging(event)) {
          this.paginator.changePage(0);
          return;
      }

      this.spinnerService.show();

      this._timeSheetServiceProxy.getTimeSheet(
          undefined, 
          undefined,
          undefined,
          undefined,
          this.filters.driver,
          this.primengTableHelper.getSorting(this.dataTable),
          this.primengTableHelper.getMaxResultCount(this.paginator, event),
          this.primengTableHelper.getSkipCount(this.paginator, event)
      ).subscribe(result => {
          this.primengTableHelper.totalRecordsCount = result.totalCount;
          this.primengTableHelper.records = result.items;
          console.log(result.items);
          this.spinnerService.hide();
      });
  }
}