import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { MatDialog } from '@angular/material/dialog';
import { OperationsApiService } from '@fleio-api/utils/operations/operations-api.service';
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 { IOperationModel } from '@fleio-api/utils/model/operation.model';
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 { OperationUiService } from './operation-ui.service';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { ApiCallAction, CallType } from '@objects-view/actions/api-call-action';

@Injectable({
  providedIn: 'root',
})
export class OperationsListUiService implements IObjectListUIService {
  public noItemsMessage = $localize`No operations`;
  private datePipe: DateFormatterPipe;

  constructor(
    private router: Router, private config: ConfigService,
    private operationsApiService: OperationsApiService,
    private matDialog: MatDialog,
  ) {
    this.datePipe = new DateFormatterPipe(this.config);
  }

  getObjectUIService(
    object: IBaseFleioObjectModel, permissions: IPermissionsModel, state: string
  ): IObjectUIService {
    return new OperationUiService(
      object as IOperationModel, permissions, state, this.router, this.config, this.operationsApiService,
      this.matDialog,
    );
  }

  getTableData(objectList: FleioObjectsList<IOperationModel>): ITableData {
    const tableData: ITableData = {
      header: {
        columns: [
          {
            type: ColumnType.Value, displayName: $localize`ID`, enableSort: false, fieldName: 'id',
            flex: '150px', hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Status`, enableSort: true, fieldName: 'status',
            flex: '100px',
          },
          {
            type: ColumnType.Value, displayName: $localize`Created at`, enableSort: true, fieldName: 'created_at',
            flex: '200px', hide: {xs: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Created by`, enableSort: false, fieldName: 'initiating_user',
            flex: '150px', hide: {xs: true, sm: true, md: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Primary object id`, enableSort: false,
            fieldName: 'primary_object_id',
            flex: '150px', hide: {xs: true, sm: true, md: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Operation type`, enableSort: false, fieldName: 'operation_type',
            flex: 'auto'
          },
          {
            type: ColumnType.Actions, displayName: $localize`Actions`, enableSort: false, fieldName: '(actions)',
            flex: 'auto', hide: {xs: true, sm: true},
          },
        ],
        columnNames: [
          'id', 'status', 'created_at', 'initiating_user', 'primary_object_id', 'operation_type', '(actions)'
        ],
        showStatus: true,
      },
      rows: [],
    };

    for (const operation of objectList.objects) {
      const rowUIService = this.getObjectUIService(operation, objectList.permissions, 'table-view');
      const notSeen = !operation.seen;
      const row: ITableRow = {
        cells: {
          id: {text: operation.id.toString(), textBold: notSeen,},
          status: {text: operation.status, textBold: notSeen,},
          created_at: {text: this.datePipe.toDateTime(operation.created_at), textBold: notSeen,},
          initiating_user: {
            text: operation.initiating_user ? operation.initiating_user.full_name || operation.initiating_user.email : $localize`n/a`,
            textBold: notSeen,
          },
          operation_type: {text: operation.operation_type, textBold: notSeen,},
          primary_object_id: {text: operation.primary_object_id, textBold: notSeen,},
        },
        icon: rowUIService.getIcon(),
        status: rowUIService.getStatus(),
        actions: rowUIService.getActions(),
        url: rowUIService.getDetailsLink(),
        object: operation,
      };

      tableData.trackByFunction = (index, item: ITableRow) => item.object.id;
      tableData.rows.push(row);
    }

    return tableData;
  }

  getActions(objectList: FleioObjectsList<IBaseFleioObjectModel>): IAction[] {
    return [
      new ApiCallAction(
        {
          icon: {name: 'visibility'},
          name: $localize`Mark all as viewed`,
          tooltip: $localize`Mark all as viewed`,
          confirmOptions: {
            confirm: true,
            title: $localize`Mark all operations as viewed`,
            message: $localize`Are you sure you want to mark all operations as viewed?`,
          },
          apiService: this.operationsApiService,
          callType: CallType.Post,
          apiAction: 'mark_all_as_read'
        }
      )
    ];
  }

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