import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IInstanceModel } from '@fleio-api/openstack/model/instance.model';
import { InstancesApiService } from '@fleio-api/openstack/instance/instances-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { ConfigService } from '@shared/config/config.service';
import { FormatHelper } from '@shared/ui-api/helpers/format-helper';
import { IPeriodTraffic, ITrafficData } from '@fleio-api/openstack/model/traffic-data.model';

@Component({
  selector: 'app-instance-details-traffic',
  templateUrl: './instance-details-traffic.component.html',
  styleUrls: ['./instance-details-traffic.component.scss']
})
export class InstanceDetailsTrafficComponent extends DetailsComponentBase<IInstanceModel> implements OnInit {
  private formatHelper = new FormatHelper();
  trafficData: ITrafficData;
  displayedColumns = ['start_dt', 'end_dt', 'in', 'out', 'total'];
  cycleTraffic: IPeriodTraffic[];
  monthTraffic: IPeriodTraffic[];

  constructor(
    private instancesApiService: InstancesApiService,
    private notificationService: NotificationService,
    public config: ConfigService,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
  ) {
    super(ngZone, changeDetectorRef, config);
  }

  protected refreshData() {
    this.instancesApiService.getTrafficData(this.object.id).subscribe({
      next: response => {
        this.trafficData = response;
        this.cycleTraffic = [];
        this.monthTraffic = [];

        for (const monthTrafficPeriod of this.trafficData.month_traffic) {
          monthTrafficPeriod.in_display = this.formatHelper.readableBytes(monthTrafficPeriod.in);
          monthTrafficPeriod.out_display = this.formatHelper.readableBytes(monthTrafficPeriod.out);
          monthTrafficPeriod.total_display = this.formatHelper.readableBytes(
            monthTrafficPeriod.in + monthTrafficPeriod.out
          );
          this.monthTraffic.push(monthTrafficPeriod);
        }

        for (const cycleTrafficPeriod of this.trafficData.cycle_traffic) {
          cycleTrafficPeriod.in_display = this.formatHelper.readableBytes(cycleTrafficPeriod.in);
          cycleTrafficPeriod.out_display = this.formatHelper.readableBytes(cycleTrafficPeriod.out);
          cycleTrafficPeriod.total_display = this.formatHelper.readableBytes(
            cycleTrafficPeriod.in + cycleTrafficPeriod.out
          );
          this.cycleTraffic.push(cycleTrafficPeriod);
        }
      }, error: () => {
        this.notificationService.showMessage($localize`Could not load traffic data.`);
      }
    });
  }

  ngOnInit() {
    super.ngOnInit();
  }
}
