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 { ClientUIService } from './client-ui.service';
import { IAction } from '@objects-view/interfaces/actions/action';
import { RouterLinkAction } from '@objects-view/actions/router-link-action';
import { NotificationService } from '@shared/ui-api/notification.service';
import { RefreshService } from '@shared/ui-api/refresh.service';
import { OrderingService } from '@shared/ui-api/ordering.service';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';

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

  constructor(
    private router: Router, private config: ConfigService, private clientsApi: ClientsApiService,
    private notificationsService: NotificationService, private refreshService: RefreshService,
    private orderingService: OrderingService,
  ) {
    this.datePipe = new DateFormatterPipe(this.config);
  }

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

  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: '1 0 150px', flexXs: '95%',
          },
          {
            type: ColumnType.Value, displayName: $localize`Roles`, enableSort: false, fieldName: 'roles',
            flex: '1 0 100px', hide: {xs: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Created at`, enableSort: false, fieldName: 'created_at',
            flex: '1 0 100px', hide: {xs: true, sm: true, md: true}
          },
          {
            type: ColumnType.Actions, displayName: $localize`Actions`, enableSort: false, fieldName: '(actions)',
            flex: 'auto',
          },
        ],
        columnNames: [
          '(image)', 'id', 'name', 'roles', 'created_at', '(actions)',
        ],
        showStatus: true,
      },
      rows: [],
    };

    for (const client of objectList.objects) {
      const rowUIService = this.getObjectUIService(client, objectList.permissions, 'uptodate_credit');
      const roles = client.roles.map(role => role.display_name).join(',');
      let nameTitle = client.name;
      if (this.config.activeClientId.toString() === client.id.toString()) {
        nameTitle += $localize` - current client`;
      }
      let text = client.name;
      let subText = '';
      if (client.company) {
        text = client.company;
        subText = client.name;
      }
      const row: ITableRow = {
        cells: {
          id: {text: `${client.id}`},
          name: {
            text: text,
            subText: subText,
            title: nameTitle,
          },
          roles: {text: roles},
          created_at: {text: this.datePipe.toDateTime(client.date_created)}
        },
        icon: rowUIService.getIcon(),
        status: rowUIService.getStatus(),
        border: rowUIService.getBorder(),
        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[] {
    return [
      new RouterLinkAction({
        name: $localize`Create new client`,
        tooltip: $localize`Create new client`,
        icon: {name: 'add'},
        router: this.router,
        routerUrl: this.config.getPanelUrl('clients/create'),
        featureName: 'clients&users.switch-client',
      })
    ];
  }

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