import { Injectable } from '@angular/core';
import { IObjectListUIService } from '@objects-view/interfaces/object-list-ui-service';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
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 { DbaasInstanceUiService } from './dbaas-instance-ui.service';
import { DbaasInstancesApiService } from '@fleio-api/openstack/dbaas/dbaas-instances-api.service';
import { IDbaasInstanceModel } from '@fleio-api/openstack/model/dbaas-instance.model';
import { MatDialog } from '@angular/material/dialog';
import { StatusType, StatusValue } from '@objects-view/interfaces/object-status';
import { ISummaryCardData } from '@objects-view/interfaces/card-data/summary-card-data';
import { OrderingService } from '@shared/ui-api/ordering.service';

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

  constructor(
    private router: Router, private config: ConfigService,
    private dbaasInstancesApiService: DbaasInstancesApiService,
    private matDialog: MatDialog,
    private orderingService: OrderingService,
  ) {
    this.datePipe = new DateFormatterPipe(this.config);
  }

  getObjectUIService(
    object: IBaseFleioObjectModel, permissions: IPermissionsModel, state: string
  ): IObjectUIService {
    return new DbaasInstanceUiService(
      object as IDbaasInstanceModel, permissions, state, this.router, this.config, this.dbaasInstancesApiService,
      this.matDialog, this.orderingService,
    );
  }

  getTableData(objectList: FleioObjectsList<IDbaasInstanceModel>): ITableData {
    const tableData: ITableData = {
      header: {
        columns: [
          {
            type: ColumnType.Image, displayName: '', enableSort: false, fieldName: '(image)',
            flex: '35px', hide: {xs: true, sm: true}
          },
          {
            type: ColumnType.Value, displayName: $localize`Name`, enableSort: true, fieldName: 'name',
            flex: '200px', flexXs: '1 0 50px',
          },
          {
            type: ColumnType.Value, displayName: $localize`Created at`,
            enableSort: true, fieldName: 'created',
            flex: '120px',
            hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Region`,
            enableSort: true, fieldName: 'region',
            flex: '150px',
          },
          {
            type: ColumnType.Value, displayName: $localize`Access IP`,
            enableSort: false, fieldName: 'access_ip',
            flex: '90px',
            hide: {xs: true, sm: true, md: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Flavor`,
            enableSort: false, fieldName: 'flavor',
            flex: '100px',
            hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Replica of`,
            enableSort: false, fieldName: 'replica_of',
            flex: '90px',
            hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Value, displayName: $localize`Client`,
            enableSort: false, fieldName: 'client',
            flex: '110px',
            hide: {xs: true, sm: true},
          },
          {
            type: ColumnType.Actions, displayName: $localize`Actions`, enableSort: false, fieldName: '(actions)',
          },
        ],
        columnNames: ['(image)', 'name', 'created', 'region', 'access_ip', 'flavor', 'replica_of', 'client', '(actions)'],
        showStatus: true,
        visibleActions: 2,
      },
      rows: [],
    };

    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: this.datePipe.transform(operation.created_at),
            title: this.datePipe.getTitleAttributeValue(operation.created_at),
          },
          region: {text: ''},
          access_ip: {text: ''},
          flavor: {text: ''},
          replica_of: {text: ''},
          client: {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 dbaasInstance of objectList.objects) {
      const uiService = this.getObjectUIService(
        dbaasInstance, objectList.permissions, 'table-view'
      ) as DbaasInstanceUiService;
      let nameSubText = dbaasInstance.status;
      if (dbaasInstance.operating_status) {
        nameSubText = $localize`${dbaasInstance.status}, ${dbaasInstance.operating_status}`;
      }
      const row: ITableRow = {
        cells: {
          name: {
            text: dbaasInstance.name || dbaasInstance.id.toString(),
            subText: nameSubText,
          },
          created: {
            text: this.datePipe.transform(dbaasInstance.created),
            title: this.datePipe.getTitleAttributeValue(dbaasInstance.created),
          },
          region: {text: dbaasInstance.region},
          access_ip: {
            text: dbaasInstance?.addresses?.length ? dbaasInstance?.addresses[0].address : $localize`n/a`,
          },
          flavor: {text: dbaasInstance.flavor?.name || $localize`n/a`},
          replica_of: {
            text: dbaasInstance.replica_of ? dbaasInstance.replica_of.name : $localize`n/a`,
            url: dbaasInstance.replica_of ? this.config.getPanelUrl(`openstack/database-instances/${dbaasInstance.replica_of.id}`) : null,
          },
          client: {
            text: dbaasInstance.client ? dbaasInstance.client.display : $localize`n/a`,
            url: dbaasInstance.client? this.config.getPanelUrl('clients-users/clients/' + dbaasInstance.client.id) : null,
          },
        },
        icon: uiService.getIcon(),
        status: uiService.getStatus(),
        actions: uiService.getActions(),
        url: uiService.getDetailsLink(),
        object: dbaasInstance,
      };

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

  getCardListPlaceholders(objectList: FleioObjectsList<IBaseFleioObjectModel>): Array<ISummaryCardData> {
    const placeholders: Array<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`Started 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;
  }

  getRefreshInterval(): number {
    return this.config.getDefaultRefreshInterval();
  }
}
