import { ChangeDetectorRef, Component, NgZone, OnDestroy, OnInit } from '@angular/core';
import { DetailsComponentBase } from '@objects-view/details-component-base';
import { IRevenueReportModel } from '@fleio-api/utils/model/revenue-report.model';
import { NavigationEnd, Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-revenue-report-overview',
  templateUrl: './revenue-report-overview.component.html',
  styleUrls: ['./revenue-report-overview.component.scss']
})
export class RevenueReportOverviewComponent extends DetailsComponentBase<IRevenueReportModel> implements OnInit, OnDestroy {
  displayedColumns: string[] = ['name', 'revenue'];
  routerSubscription: Subscription;

  constructor(
    private router: Router,
    private config: ConfigService,
    ngZone: NgZone,
    changeDetectorRef: ChangeDetectorRef,
  ) {
    super(ngZone, changeDetectorRef, config);
    this.routerSubscription = this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        this.setTotalRevenue();
      }
    });
  }

  setTotalRevenue() {
    if (this.object) {
      if (!this.object.total_revenue_per_location || !this.object.total_revenue_per_location.length) {
        this.object.total_revenue_per_location = [];
      }
      this.object.total_revenue_per_location.push({
        name: $localize`All locations`,
        revenue: this.object.total_revenue
      });
    }
  }

  ngOnInit(): void {
    super.ngOnInit();
    this.setTotalRevenue();
  }

  ngOnDestroy() {
    super.ngOnDestroy();
    if (this.routerSubscription) {
      this.routerSubscription.unsubscribe();
      this.routerSubscription = null;
    }
  }

}
