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

@Component({
  selector: 'app-entity-audit-log',
  templateUrl: './entity-audit-log.component.html',
  styleUrls: ['./entity-audit-log.component.scss']
})
export class EntityAuditLogComponent extends DetailsComponentBase<IBaseFleioObjectModel> implements OnInit {
  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);
  }

  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();
    let filteringString = `logtoentity__entity_type:${this.data.entity_type}+logtoentity__entity_id:${this.object.id}`;
    if (this.data?.entity_additional_identifier) {
      filteringString += `+logtoentity__entity_id:${this.object[this.data.entity_additional_identifier]}`
    }
    if (this.data?.additional_entity_id) {
      filteringString += `+logtoentity__entity_id:${this.data.additional_entity_id}`
    }
    if (this.data?.additional_entity_type) {
      filteringString += `+logtoentity__entity_type:${this.data.additional_entity_type}`
    }

    this.objectListController = new ObjectListController<ObjectController>(
      this.activityLogApiService.list({
        filtering: filteringString,
        page_size: this.currentPageSize,
        ordering: OrderingHelper.toStr(this.sort),
      }).pipe(map(data => {
        this.loading = false;
        return data;
      })),
      this.activityLogListUiService,
    );
  }
}
