import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { IObjectListUIService } from '@objects-view/interfaces/object-list-ui-service';
import { ConfigService } from '@shared/config/config.service';
import { IBaseFleioObjectModel } from '@fleio-api/base-model/base-fleio-object.model';
import { IPermissionsModel } from '@fleio-api/base-model/IPermissionsModel';
import { IObjectUIService } from '@objects-view/interfaces/object-ui-service';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
import { ITableData } from '@objects-view/interfaces/table-data/table-data';
import { ColumnType } from '@objects-view/interfaces/table-data/column-definition';
import { ITableRow } from '@objects-view/interfaces/table-data/table-row';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { RevenueReportUiService } from './revenue-report-ui.service';
import { IRevenueReportModel } from '@fleio-api/utils/model/revenue-report.model';
import { RevenueReportsApiService } from '@fleio-api/utils/revenue-reports/revenue-reports-api.service';
import { RouterLinkAction } from '@objects-view/actions/router-link-action';
import { CurrencyFormatterPipe } from '@shared/ui/common/pipes/currency-formatter.pipe';

@Injectable({
  providedIn: 'root',
})
export class RevenueReportsListUiService implements IObjectListUIService {
  public noItemsMessage = $localize`No revenue reports`;
  private datePipe: DateFormatterPipe;
  private currencyPipe: CurrencyFormatterPipe;
  constructor(
    private router: Router, private config: ConfigService,
    private revenueReportsApiService: RevenueReportsApiService,
    private matDialog: MatDialog,
    ) {
    this.datePipe = new DateFormatterPipe(this.config);
    this.currencyPipe = new CurrencyFormatterPipe(this.config);
  }

  getObjectUIService(
    object: IBaseFleioObjectModel, permissions: IPermissionsModel, state: string
  ): IObjectUIService {
      return new RevenueReportUiService(
        object as IRevenueReportModel, permissions, state, this.router, this.config, this.revenueReportsApiService,
        this.matDialog,
      );
  }

  getTableData(objectList: FleioObjectsList<IRevenueReportModel>): ITableData {
    const tableData: ITableData = {
      header: {
        columns: [
          { type: ColumnType.Value, displayName: $localize`Report for`, enableSort: false, fieldName: 'report_month_year' },
          { type: ColumnType.Value, displayName: $localize`Total revenue`, enableSort: false, fieldName: 'total_revenue',
            hide: {xs: true} },
          { type: ColumnType.Image, displayName: $localize`Finished generation`, enableSort: false, fieldName: 'generating' },
          { type: ColumnType.Value, displayName: $localize`Clients processed`, enableSort: false, fieldName: 'processed',
            hide: {xs: true}},
          { type: ColumnType.Actions, displayName: $localize`Actions`, enableSort: false, fieldName: '(actions)' },
        ],
        columnNames: [
          'report_month_year', 'total_revenue', 'generating', 'processed', '(actions)'
        ],
        showStatus: true,
      },
      rows: [],
    };

    for (const revenueReport of objectList.objects) {
      const rowUIService = this.getObjectUIService(revenueReport, objectList.permissions, 'table-view');
      const row: ITableRow = {
        cells: {
          report_month_year: { text: revenueReport.report_month_year},
          total_revenue: {
            text: this.currencyPipe.transform(
              revenueReport.total_revenue, revenueReport.currency_code, this.config.authService.currencyDisplayMode
            )
          },
          processed: { text: `${revenueReport.processed}%`},
        },
        icon: rowUIService.getIcon(),
        status: rowUIService.getStatus(),
        actions: rowUIService.getActions(),
        url: rowUIService.getDetailsLink(),
      };

      tableData.rows.push(row);
    }

    return tableData;
  }

  getActions(objectList: FleioObjectsList<IBaseFleioObjectModel>): IAction[] {
    return [
      new RouterLinkAction({
        name: $localize`Generate report`,
        tooltip: $localize`Generate report`,
        icon: {name: 'add'},
        router: this.router,
        routerUrl: this.config.getPanelUrl('utilities/reports/revenue-reports/generate'),
        noPermissions: !objectList.permissions['revenue_reports.trigger_revenue_report_generation'],
      })
    ];
  }

  getRefreshInterval(): number {
    if (this.config && this.config.current && this.config.current.settings &&
      this.config.current.settings.refreshIntervals) {
      return this.config.current.settings.refreshIntervals.defaultInterval;
    }
    return 10000;
  }
}
