import { Component, Input, OnInit } from '@angular/core';
import { IServiceDynamicUsageModel, ITaxDetails } 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(metric: any) {
    this.matDialog.open(
      MetricDetailDialogComponent, {
        data: {
          detailData: this.getMetricDetailData(metric),
          currency: this.dynamicUsage.usage.currency.code,
        },
        autoFocus: false,
      }).afterClosed().subscribe(() => {
    });
  }

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

  getStandardTax(tax: ITaxDetails) {
    return this.dynamicUsage.standard_price_taxes.find(t => t.name === tax.name) || null;
  }
}
