import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IPeriodicTaskLogModel } from '@fleio-api/logger/model/periodic-task-log.model';
import { Sort } from '@angular/material/sort';
import { ObjectListController } from '@objects-view/object-list-controller';
import { ObjectController } from '@objects-view/object-controller';
import { OrderingHelper } from '@shared/ui-api/helpers/ordering-helper';
import { map } from 'rxjs/operators';
import { PaginatorService } from '@shared/ui-api/paginator.service';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { ConfigService } from '@shared/config/config.service';
import { EmailMessageLogApiService } from '@fleio-api/logger/emai-message-log-api.service';
import { EmailMessageLogListUiService } from '../../../email-message-log/email-message-log-list-ui.service';

@Component({
  selector: 'app-periodic-task-log-details-emails',
  templateUrl: './periodic-task-log-details-emails.component.html',
  styleUrls: ['./periodic-task-log-details-emails.component.scss']
})
export class PeriodicTaskLogDetailsEmailsComponent extends
  DetailsComponentBase<IPeriodicTaskLogModel> implements OnInit {
  objectListController;
  currentPageSize = this.paginator.defaultPageSize;
  sort = {active: 'created_at', direction: 'desc'} as Sort;
  loading = false;

  constructor(
    public paginator: PaginatorService,
    private clientsApi: ClientsApiService,
    private emailMessageLogApiService: EmailMessageLogApiService,
    private emailMessageLogListUiService: EmailMessageLogListUiService,
    public config: ConfigService,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
  ) {
    super(ngZone, changeDetectorRef, config);
  }

  protected tabActivated() {
    super.tabActivated();
    this.loadEmailLog();
  }

  ngOnInit() {
    super.ngOnInit();
  }

  increasePageSize() {
    this.currentPageSize += this.paginator.defaultPageSize;
    this.loadEmailLog();
  }

  sortFn(data: Sort) {
    this.sort = data;
    this.loadEmailLog();
  }

  loadEmailLog() {
    this.loading = true;
    this.objectListController = null;
    this.changeDetectorRef.detectChanges();
    this.objectListController = new ObjectListController<ObjectController>(
      this.emailMessageLogApiService.list({
        periodic_task_log: this.object.id,
        page_size: this.currentPageSize,
        ordering: OrderingHelper.toStr(this.sort),
      }).pipe(map(data => {
        this.loading = false;
        return data;
      })),
      this.emailMessageLogListUiService
    );
  }

}
