import { Injectable } from '@angular/core';
import { IObjectListUIService } from '@objects-view/interfaces/object-list-ui-service';
import { ConfigService } from '@shared/config/config.service';
import { Router } from '@angular/router';
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 { RouterLinkAction } from '@objects-view/actions/router-link-action';
import { FloatingIpsApiService } from '@fleio-api/openstack/floating-ips/floating-ips-api.service';
import { FloatingIpUiService } from './floating-ip-ui.service';
import { IFloatingIpModel } from '@fleio-api/openstack/floating-ips/model/floating-ip.model';
import { MatDialog } from '@angular/material/dialog';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';

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

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

  getObjectUIService(
    object: IBaseFleioObjectModel, permissions: IPermissionsModel, state: string
  ): IObjectUIService {
    return new FloatingIpUiService(
      object as IFloatingIpModel, permissions, state, this.router, this.config, this.floatingIpsApiService,
      this.matDialog,
    );
  }

  getTableData(objectList: FleioObjectsList<IFloatingIpModel>): ITableData {
    const tableData: ITableData = {
      header: {
        columns: [
          {
            type: ColumnType.Value, displayName: $localize`IP address`,
            enableSort: true, fieldName: 'floating_ip_address',
            flex: '1 0 80px',
          },
          {
            type: ColumnType.Value, displayName: $localize`Network`, enableSort: true, fieldName: 'floating_network',
            flex: '1 0 80px', hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Created at`, enableSort: true, fieldName: 'created_at',
            flex: '1 0 120px', hide: {xs: true, sm: true, md: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Associated object`, enableSort: true,
            fieldName: 'associated_object',
            flex: '1 0 100px', hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Region`, enableSort: false, fieldName: 'region',
            flex: '1 0 100px',
          },
          {
            type: ColumnType.Actions, displayName: $localize`Actions`, enableSort: false, fieldName: '(actions)',
          },
        ],
        columnNames: [
          'floating_ip_address', 'floating_network', 'created_at', 'associated_object', 'region', '(actions)'
        ],
        showStatus: true,
      },
      rows: [],
    };

    for (const floatingIp of objectList.objects) {
      const floatingIpUiService = this.getObjectUIService(
        floatingIp, objectList.permissions, 'table-view'
      ) as FloatingIpUiService;
      let associatedObjectUrl = null;
      if (floatingIp.associated_object?.device_type === 'instance') {
         associatedObjectUrl = this.config.getPanelUrl(
           `openstack/instances/${floatingIp.associated_object.id}`
         );
      }
      const row: ITableRow = {
        cells: {
          floating_ip_address: {text: floatingIp.floating_ip_address || $localize`n/a`, subText: floatingIp.status},
          floating_network: {text: floatingIp.floating_network.name},
          created_at: {
            text: this.datePipe.transform(floatingIp.created_at),
            title: this.datePipe.getTitleAttributeValue(floatingIp.created_at),
          },
          associated_object: {
            text: floatingIp.associated_object?.name || floatingIp.associated_object?.id.toString() || $localize`n/a`,
            url: associatedObjectUrl,
          },
          region: {text: floatingIp.floating_network.region},
        },
        icon: floatingIpUiService.getIcon(),
        status: floatingIpUiService.getStatus(),
        actions: floatingIpUiService.getActions(),
        url: floatingIpUiService.getDetailsLink(),
        object: floatingIp,
      };

      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 floating ip`,
        tooltip: $localize`Create floating ip`,
        icon: {name: 'add'},
        router: this.router,
        routerUrl: this.config.getPanelUrl('openstack/floating-ips/create'),
        noPermissions: !objectList.permissions['floatingips.create'],
      })
    ];
  }

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