import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { IBaseFleioObjectModel } from '@fleio-api/base-model/base-fleio-object.model';
import { IObjectListUIService } from '@objects-view/interfaces/object-list-ui-service';
import { IPermissionsModel } from '@fleio-api/base-model/IPermissionsModel';
import { ConfigService } from '@shared/config/config.service';
import { IObjectUIService } from '@objects-view/interfaces/object-ui-service';
import { ITableData } from '@objects-view/interfaces/table-data/table-data';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
import { ITableRow } from '@objects-view/interfaces/table-data/table-row';
import { ColumnType } from '@objects-view/interfaces/table-data/column-definition';
import { IClientModel } from '@fleio-api/client-user/model/client.model';
import { ClientsApiService } from '@fleio-api/client-user/client/clients-api.service';
import { MassMessageUiService } from './mass-message-ui.service';
import { IAction } from '@objects-view/interfaces/actions/action';
import { RouterLinkAction } from '@objects-view/actions/router-link-action';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';

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

  constructor(
    private router: Router, private config: ConfigService, private clientsApi: ClientsApiService,
  ) {
    this.datePipe = new DateFormatterPipe(this.config);
  }

  getObjectUIService(
    object: IBaseFleioObjectModel, permissions: IPermissionsModel, state: string
  ): IObjectUIService {
    return new MassMessageUiService(
      object as IClientModel, permissions, state, this.router, this.config, this.clientsApi,
    );
  }

  getTableData(objectList: FleioObjectsList<IClientModel>): ITableData {
    const tableData: ITableData = {
      header: {
        columns: [
          {
            type: ColumnType.Image, displayName: '', enableSort: false, fieldName: '(image)',
            flex: '50px',
          },
          {
            type: ColumnType.Value, displayName: $localize`ID`, enableSort: false, fieldName: 'id',
            flex: '70px', hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Name`, enableSort: false, fieldName: 'name',
            flex: '350px', flexXs: '1 0 150px',
          },
          {
            type: ColumnType.Value, displayName: $localize`Up-to-date credit`, enableSort: true, fieldName: 'uptodate_credit',
            flex: '140px', hide: {sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Out of credit`, enableSort: false, fieldName: 'outofcredit_datetime',
            flex: '100px', hide: {xs: true, sm: true, md: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Configuration`, enableSort: true, fieldName: 'configuration_name',
            flex: '110px', hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Group`, enableSort: true, fieldName: 'group_name',
            flex: '100px', hide: {xs: true, sm: true, md: true},
          },
          {
            type: ColumnType.Actions, displayName: $localize`Actions`, enableSort: false, fieldName: '(actions)',
            flex: '1 0 100px',
          },
        ],
        columnNames: [
          '(image)', 'id', 'name', 'uptodate_credit', 'outofcredit_datetime', 'configuration_name',
          'group_name', '(actions)',
        ],
        showStatus: true,
      },
      rows: [],
    };

    for (const client of objectList.objects) {
      const rowUIService = this.getObjectUIService(client, objectList.permissions, 'uptodate_credit');
      const row: ITableRow = {
        cells: {
          id: {text: `${client.id}`},
          name: {
            text: client.name,
            subText: client.company
          },
          uptodate_credit: {text: `${client.uptodate_credit ? client.uptodate_credit : 0} ${client.currency}`},
          outofcredit_datetime: {
            text: client.outofcredit_datetime ? this.datePipe.toDateTime(client.outofcredit_datetime) : $localize`n/a`,
          },
          configuration_name: {text: client.configuration_name},
          group_name: {text: client.group_name || $localize`n/a`},
          company: {text: client.company},
        },
        icon: rowUIService.getIcon(),
        status: rowUIService.getStatus(),
        url: rowUIService.getDetailsLink(),
        actions: rowUIService.getActions(),
        object: client,
      };

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

    return tableData;
  }

  getActions(objectList: FleioObjectsList<IBaseFleioObjectModel>): IAction[] {
    const canMessage = !(!objectList.objects || objectList.objects.length === 0);
    let tooltip;
    if (canMessage) {
      tooltip = $localize`Message filtered clients`;
    } else {
      tooltip = $localize`No clients selected`;
    }
    return [
      new RouterLinkAction({
        name: $localize`Message filtered clients`,
        tooltip,
        icon: {name: 'mail'},
        router: this.router,
        routerUrl: this.config.getPanelUrl('clients-users/mass-message/send-mass-message'),
        queryParamsHandling: 'preserve',
        noPermissions: !objectList.permissions['clients.send_mass_message'],
        disabled: !canMessage
      }),
    ];
  }

  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;
  }
}
