import { Component, Input, OnInit } from '@angular/core';
import { IServiceDynamicUsageModel } from '@fleio-api/billing/model/service-dynamic-usage.model';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { MatDialog } from '@angular/material/dialog';
import { MetricDetailDialogComponent } from '@shared/common-dialogs/service-dynamic-usage/metric-detail-dialog/metric-detail-dialog.component';
import { AuthService } from '@shared/auth/auth.service';
import { ConfigService } from '@shared/config/config.service';
import { PriceOverrideModel } from '@fleio-api/billing/model/service.model';

@Component({
  selector: 'app-fleio-service-dynamic-usage',
  templateUrl: './fleio-service-dynamic-usage.component.html',
  styleUrls: ['./fleio-service-dynamic-usage.component.scss'],
  animations: [
    trigger('detailExpand', [
      state('collapsed', style({height: '0px', minHeight: '0'})),
      state('expanded', style({height: '*'})),
      transition('expanded <=> collapsed', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')),
    ]),
  ],
})
export class FleioServiceDynamicUsageComponent implements OnInit {
  @Input() dynamicUsage: IServiceDynamicUsageModel;
  @Input() allowMetricDetails = true;
  public isFree = false;
  public readonly detailColumns = ['name', 'region', 'price'];
  public readonly metricsDetailColumns = ['name', 'region', 'price'];
  expandedElement: object;

  constructor(
    private matDialog: MatDialog,
    public auth: AuthService,
    public config: ConfigService,
  ) {
  }

  ngOnInit() {
    this.isFree = this.dynamicUsage.price_override && this.dynamicUsage.price_override_model === PriceOverrideModel.FreeService;
  }

  showMetricDetail(metricName: string) {
    this.matDialog.open(
      MetricDetailDialogComponent, {
        data: {
          detailData: this.getMetricDetailData(metricName),
          currency: this.dynamicUsage.usage.currency.code,
        },
        autoFocus: false,
      }).afterClosed().subscribe(() => {
    });
  }

  getMetricDetailData(metricName: string) {
    const list = [];
    for (const metric of this.dynamicUsage.usage.metrics_details) {
      if (metric.name === metricName) {
        list.push(metric);
      }
    }
    return list;
  }
}
