import { Component, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IInstanceModel } from '@fleio-api/openstack/model/instance.model';
import { IInstanceHistoryLogModel } from '@fleio-api/openstack/model/instance-history-log.model';
import { InstancesApiService } from '@fleio-api/openstack/instance/instances-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
import { ConfigService } from '@shared/config/config.service';
import { PaginatorService } from '@shared/ui-api/paginator.service';

@Component({
  selector: 'app-enduser-instance-details-history-log',
  templateUrl: './enduser-instance-details-history-log.component.html',
  styleUrls: ['./enduser-instance-details-history-log.component.scss']
})
export class EnduserInstanceDetailsHistoryLogComponent extends DetailsComponentBase<IInstanceModel> implements OnInit {
  historyLogs: IInstanceHistoryLogModel[];
  loading: boolean;
  nextPage = false;
  previousPage = false;
  marker = null;
  markerHistory: Array<string> = [];
  displayedColumns: string[] = ['date', 'message'];

  constructor(
    public config: ConfigService,
    private instancesApiService: InstancesApiService,
    private notificationService: NotificationService,
    public paginator: PaginatorService,
  ) {
    super();
  }

  changePage(action: string) {
    if (action === 'next') {
      this.marker = this.historyLogs[this.historyLogs.length - 1].request_id;
      this.markerHistory.push(this.marker);
    }
    if (action === 'previous') {
      this.markerHistory.pop();
      if (!this.markerHistory.length) {
        this.marker = null;
      } else {
        this.marker = this.markerHistory[this.markerHistory.length - 1];
      }
    }
    this.loadHistoryLog();
  };

  private loadHistoryLog() {
    this.loading = true;
    this.instancesApiService.getActions(
      this.object.id, this.paginator.defaultPageSize, this.marker,
    ).subscribe({
      next: (response: FleioObjectsList<IInstanceHistoryLogModel>) => {
        this.historyLogs = response.objects;
        this.nextPage = response.hasMore;
        this.previousPage = !!this.marker;
        this.loading = false;
      }, error: () => {
        this.loading = false;
        this.notificationService.showMessage($localize`Could not load history logs.`);
      }
    });
  }

  protected initTabData() {
    super.initTabData();
    this.loadHistoryLog();
  }

  ngOnInit() {
    super.ngOnInit();
  }

}
