import { ChangeDetectorRef, Component, NgZone, OnDestroy, OnInit } from '@angular/core';
import { Sort } from '@angular/material/sort';
import { PaginatorService } from '@shared/ui-api/paginator.service';
import { ConfigService } from '@shared/config/config.service';
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 { ActivityLogApiService } from '@fleio-api/utils/activity-log/activity-log-api.service';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IUserModel } from '@fleio-api/client-user/model/user.model';
import { ActivityLogListUiService } from '../../../../utils/activity-log/activity-log-list-ui.service';

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

  constructor(
    public paginator: PaginatorService,
    private activityLogApiService: ActivityLogApiService,
    private activityLogListUiService: ActivityLogListUiService,
    public config: ConfigService,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
  ) {
    super(ngZone, changeDetectorRef, config);
    this.activityLogListUiService.showUser = false;
  }

  ngOnDestroy() {
    super.ngOnDestroy();
    this.activityLogListUiService.showUser = true;
  }

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

  ngOnInit() {
    super.ngOnInit();
  }

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

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

  loadLog() {
    this.loading = true;
    this.objectListController = null;
    this.changeDetectorRef.detectChanges();
    this.objectListController = new ObjectListController<ObjectController>(
      this.activityLogApiService.list({
        filtering: `user:${this.object.id}`,
        page_size: this.currentPageSize,
        ordering: OrderingHelper.toStr(this.sort),
      }).pipe(map(data => {
        this.loading = false;
        return data;
      })),
      this.activityLogListUiService,
    );
  }
}
