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 { IInstanceModel } from '@fleio-api/openstack/model/instance.model';
import { IObjectUIService } from '@objects-view/interfaces/object-ui-service';
import { InstanceUIService } from './instance-ui.service';
import { InstancesApiService } from '@fleio-api/openstack/instance/instances-api.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 { IAction } from '@objects-view/interfaces/actions/action';
import { RouterLinkAction } from '@objects-view/actions/router-link-action';
import { MatDialog } from '@angular/material/dialog';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { ISummaryCardData } from '@objects-view/interfaces/card-data/summary-card-data';
import { StatusType, StatusValue } from '@objects-view/interfaces/object-status';
import { NotificationService } from '@shared/ui-api/notification.service';

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

  constructor(
    private router: Router, private config: ConfigService, private instancesApi: InstancesApiService,
    private matDialog: MatDialog,
    private notificationService: NotificationService,
  ) {
    this.datePipe = new DateFormatterPipe(this.config);
  }

  getObjectUIService(
    object: IBaseFleioObjectModel, permissions: IPermissionsModel, state: string
  ): IObjectUIService {
    return new InstanceUIService(
      object as IInstanceModel, permissions, state, this.router, this.config, this.instancesApi, this.matDialog,
      this.notificationService,
    );
  }

  getTableData(objectList: FleioObjectsList<IInstanceModel>): ITableData {
    const columns = [
      {
        type: ColumnType.Image, displayName: '', enableSort: false, fieldName: '(image)',
        flex: '35px'
      },
      {
        type: ColumnType.Value, displayName: $localize`Name`, enableSort: true, fieldName: 'name',
        flex: '25%', flexXs: '150px'
      },
      {
        type: ColumnType.Value, displayName: $localize`Created at`, enableSort: true, fieldName: 'created',
        flex: '110px', hide: {xs: true, sm: true, md: true},
      },
    ];
    const columnNames = ['(image)', 'name', 'created'];
    if (this.config.authService.feature('openstack.instances.show_hypervisors')) {
      columns.push({
        type: ColumnType.Value, displayName: $localize`Hypervisor`, enableSort: false, fieldName: 'host_name',
        flex: '100px', hide: {xs: true, sm: true, md: true},
      });
      columnNames.push('host_name');
    }
    columns.push.apply(columns, [
      {
        type: ColumnType.Value, displayName: $localize`Avail. zone`, enableSort: true,
        fieldName: 'availability_zone', flex: '120px', hide: {xs: true},
      },
      {
        type: ColumnType.Value, displayName: $localize`Access IP`, enableSort: false, fieldName: 'access_ip',
        flex: '120px',
      },
      {
        type: ColumnType.Value, displayName: $localize`Flavor`, enableSort: false, fieldName: 'flavor',
        flex: '90px', hide: {xs: true, sm: true},
      },
      {
        type: ColumnType.Value, displayName: $localize`Region`, enableSort: true, fieldName: 'region',
        flex: '90px', hide: {xs: true, sm: true},
      },
      {
        type: ColumnType.Actions, displayName: $localize`Actions`, enableSort: false, fieldName: '(actions)',
      },
    ]);
    columnNames.push.apply(columnNames, ['availability_zone', 'access_ip', 'flavor', 'region', '(actions)']);
    const tableData: ITableData = {
      header: {
        columns,
        columnNames,
        showStatus: true,
        visibleActions: 0,
      },
      rows: [],
    };
    const datePipe = new DateFormatterPipe(this.config);
    const operationsEnabled = this.config.authService.feature('utils.operations');

    for (const operation of objectList.operations) {
      const row: ITableRow = {
        cells: {
          name: {text: $localize`Creating ${operation.name}`},
          created: {
            text: datePipe.transform(operation.created_at),
            title: datePipe.getTitleAttributeValue(operation.created_at)
          },
          host_name: {text: ''},
          access_ip: {text: ''},
          flavor: {text: ''},
          region: {text: ''},
        },
        icon: {name: 'refresh'},
        status: {type: StatusType.Changing, value: StatusValue.Waiting},
        url: operationsEnabled ? this.config.getPanelUrl('utilities/operations', operation.id) : null,
        object: operation,
      };
      tableData.rows.push(row);
    }

    for (const instance of objectList.objects) {
      const rowUIService = this.getObjectUIService(instance, objectList.permissions, 'table-view');
      const row: ITableRow = {
        cells: {
          name: {text: instance.name, subText: instance.display_status.toLocaleUpperCase()},
          created: {
            text: datePipe.transform(instance.created),
            title: datePipe.getTitleAttributeValue(instance.created)
          },
          host_name: {text: instance.host_name},
          availability_zone: {text: instance.availability_zone},
          access_ip: {text: instance.access_ip},
          flavor: {text: instance.flavor ? instance.flavor.name : $localize`n/a`},
          region: {text: instance.region},
        },
        icon: rowUIService.getIcon(),
        status: rowUIService.getStatus(),
        actions: rowUIService.getActions(),
        url: rowUIService.getDetailsLink(),
        object: instance,
      };

      tableData.rows.push(row);
    }

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

  getActions(objectList: FleioObjectsList<IBaseFleioObjectModel>): IAction[] {
    return [
      new RouterLinkAction({
        name: $localize`Create new instance`,
        tooltip: $localize`Create new instance`,
        icon: {name: 'add'},
        router: this.router,
        routerUrl: this.config.getPanelUrl('openstack/instances/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;
  }

  getCardListPlaceholders(objectList: FleioObjectsList<IBaseFleioObjectModel>): ISummaryCardData[] {
    const placeholders: ISummaryCardData[] = [];
    const operationsEnabled = this.config.authService.feature('utils.operations');

    for (const operation of objectList.operations) {
      placeholders.push(
        {
          header: {
            title: {
              text: $localize`Creating ${operation.name}`,
            },
            status: {type: StatusType.Changing, value: StatusValue.Waiting},
            icon: {name: 'refresh'},
          },
          object: operation,
          fields: [
            {
              name: $localize`Operation ID`,
              value: operation.id,
            },
            {
              name: $localize`Created at`,
              value: this.datePipe.transform(operation.created_at),
              title: this.datePipe.getTitleAttributeValue(operation.created_at),
            },
          ],
          detailsLink: {
            url: operationsEnabled ? this.config.getPanelUrl('utilities/operations', operation.id) : null,
            enabled: true,
          }
        }
      );
    }

    return placeholders;
  }
}
