import { ObjectUIServiceBase } from '@objects-view/object-ui-service-base';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { IPermissionsModel } from '@fleio-api/base-model/IPermissionsModel';
import { IObjectStatus, StatusType, StatusValue } from '@objects-view/interfaces/object-status';
import { IIcon } from '@shared/ui/common/interfaces/icon';
import { ITitle } from '@objects-view/interfaces/card-data/card-title';
import { IAction } from '@objects-view/interfaces/actions/action';
import { RouterLinkAction } from '@objects-view/actions/router-link-action';
import { CallbackAction } from '@objects-view/actions/callback-action';
import { IDataField } from '@objects-view/interfaces/card-data/data-field';
import { IDetailsTab } from '@objects-view/interfaces/details/details-tab';
import { ApiCallAction, CallType } from '@objects-view/actions/api-call-action';
import { IDbaasInstanceModel } from '@fleio-api/openstack/model/dbaas-instance.model';
import { DbaasInstancesApiService } from '@fleio-api/openstack/dbaas/dbaas-instances-api.service';
import { map } from 'rxjs/operators';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import {
  ResizeDatabaseInstanceVolumeDialogComponent
} from '@shared/common-dialogs/openstack/dbaas/resize-database-instance-volume-dialog/resize-database-instance-volume-dialog.component';
import { MatDialog } from '@angular/material/dialog';
import {
  AddDatabaseReplicaDialogComponent
} from '@shared/common-dialogs/openstack/dbaas/add-database-replica-dialog/add-database-replica-dialog.component';
import {
  RenameDatabaseInstanceDialogComponent
} from '@shared/common-dialogs/openstack/dbaas/rename-database-instance-dialog/rename-database-instance-dialog.component';
import {
  UpdateDatabaseAccessibilityDialogComponent
} from '@shared/common-dialogs/openstack/dbaas/update-database-accessibility-dialog/update-database-accessibility-dialog.component';
import { OrderingService } from '@shared/ui-api/ordering.service';
import {
  DbaasInstanceCreateFormComponent
} from '@shared/common-tabs/openstack/dbaas/dbaas-instance-create-form/dbaas-instance-create-form.component';
import {
  DbaasInstanceUsersTabComponent
} from '@shared/common-tabs/openstack/dbaas/dbaas-instance-users-tab/dbaas-instance-users-tab.component';
import {
  DbaasInstanceDatabasesTabComponent
} from '@shared/common-tabs/openstack/dbaas/dbaas-instance-databases-tab/dbaas-instance-databases-tab.component';
import {
  DbaasInstanceOverviewTabComponent
} from '@shared/common-tabs/openstack/dbaas/dbaas-instance-overview-tab/dbaas-instance-overview-tab.component';
import {
  DbaasInstanceRootUserTabComponent
} from '@shared/common-tabs/openstack/dbaas/dbaas-instance-root-user-tab/dbaas-instance-root-user-tab.component';
import {
  DbaasInstanceResizeFlavorFormComponent
} from '@shared/common-tabs/openstack/dbaas/dbaas-instance-resize-flavor-form/dbaas-instance-resize-flavor-form.component';
import { EntityAuditLogComponent } from '../../common-components/entity-audit-log/entity-audit-log.component';
import {
  AddDatabaseBackupDialogComponent
} from '@shared/common-dialogs/openstack/dbaas/add-database-backup-dialog/add-database-backup-dialog.component';
import {
  DbaasInstanceBackupsTabComponent
} from '@shared/common-tabs/openstack/dbaas/dbaas-instance-backups-tab/dbaas-instance-backups-tab.component';
import {
  DbaasInstanceLogsComponent
} from '@shared/common-tabs/openstack/dbaas/dbaas-instance-logs/dbaas-instance-logs.component';
import {
  DbaasInstanceBackupSchedulesComponent
} from '@shared/common-tabs/openstack/dbaas/dbaas-instance-backup-schedules/dbaas-instance-backup-schedules.component';

export class DbaasInstanceUiService extends ObjectUIServiceBase<IDbaasInstanceModel> {
  private readonly datePipe: DateFormatterPipe;

  constructor(
    object: IDbaasInstanceModel, permissions: IPermissionsModel, state: string,
    private router: Router, private config: ConfigService, private dbaasInstancesApiService: DbaasInstancesApiService,
    private matDialog: MatDialog, private orderingService: OrderingService,
  ) {
    super(object, permissions, state);
    this.datePipe = new DateFormatterPipe(this.config);
  }

  getIcon(): IIcon {
    if (this.state === 'create') {
      return null;
    }
    return {
      name: 'database',
      class: 'fl-icons',
      marginTop: '3px',
    };
  }

  getStatus(): IObjectStatus {
    switch (this.object.status) {
      case 'ACTIVE':
        return {type: StatusType.Defined, value: StatusValue.Active};
      case 'REBOOT':
      case 'NEW':
      case 'BUILD':
      case 'SHUTDOWN':
      case 'RESIZE':
      case 'UPGRADE':
      case 'PROMOTE':
      case 'EJECT':
      case 'DETACH':
      case 'BACKUP':
        return {type: StatusType.Changing, value: StatusValue.Waiting};
      case 'RESTART_REQUIRED':
        return {type: StatusType.Defined, value: StatusValue.Warning};
      case 'ERROR':
        return {type: StatusType.Defined, value: StatusValue.Error};
      default:
        return {type: StatusType.None, value: StatusValue.None};
    }
  }

  getTitle(): ITitle {
    switch (this.state) {
      case 'create':
        return {
          text: $localize`Create new database instance`,
        };

      default:
        let subText = this.object.status;
        if (this.object.operating_status) {
          subText = $localize`${this.object.status}, ${this.object.operating_status}`;
        }
        return {
          text: `${this.object.name || this.object.id.toString()}`,
          subText,
        };
    }
  }

  getActions(): IAction[] {
    const actions: IAction[] = [];

    if (this.object.status === 'ACTIVE') {
      actions.push(new ApiCallAction(
        {
          object: this.object,
          icon: {name: 'reboot', class: 'fl-icons'},
          name: $localize`Restart database service`,
          tooltip: $localize`Restart database service`,
          confirmOptions: {
            confirm: true,
            title: $localize`Restart database service`,
            message: $localize`Are you sure you want to restart database service for instance ${this.object.id}?`,
            importantMessage: $localize`The database service is unavailable until the instance restart finishes.`,
          },
          successMessage: $localize`Restart queued`,
          apiService: this.dbaasInstancesApiService,
          apiAction: 'restart',
          callType: CallType.Post,
          refreshAfterExecute: true,
          redirectAfterExecute: false,
          noPermissions: !this.permissions['dbaas-instances.restart'],
        }
      ));

      if (!this.object?.replica_of) {
        actions.push(new CallbackAction(
          {
            object: this.object,
            icon: {name: 'plus_one'},
            tooltip: $localize`Create replica`,
            name: $localize`Create replica`,
            refreshAfterExecute: true,
            featureName: 'openstack.dbaas.replicas',
            callback: () => this.matDialog.open(
              AddDatabaseReplicaDialogComponent, {
                data: {
                  database_instance: this.object
                },
                autoFocus: false,
              }).afterClosed().pipe(map(result => ({message: result} as IActionResult))),
            noPermissions: !this.permissions['dbaas-instances.create_replica'],
          }
        ));
      }

      actions.push(new CallbackAction(
        {
          object: this.object,
          icon: {name: 'backup'},
          tooltip: $localize`Create backup`,
          name: $localize`Create backup`,
          refreshAfterExecute: true,
          callback: () => this.matDialog.open(
            AddDatabaseBackupDialogComponent, {
              data: {
                database_instance: this.object
              },
              autoFocus: false,
            }).afterClosed().pipe(map(result => ({message: result} as IActionResult))),
          noPermissions: !this.permissions['dbaas-instances.create_backup'],
          featureName: 'openstack.dbaas.backups',
        }
      ));

      actions.push(new CallbackAction(
        {
          object: this.object,
          icon: {name: 'lock'},
          tooltip: $localize`Update accessibility`,
          name: $localize`Update accessibility`,
          refreshAfterExecute: true,
          callback: () => this.matDialog.open(
            UpdateDatabaseAccessibilityDialogComponent, {
              data: {
                database_instance: this.object
              },
              autoFocus: false,
            }).afterClosed().pipe(map(result => ({message: result} as IActionResult))),
          noPermissions: !this.permissions['dbaas-instances.update_accessibility'],
        }
      ));

      actions.push(new CallbackAction(
        {
          object: this.object,
          icon: {name: 'aspect_ratio'},
          tooltip: $localize`Resize volume`,
          name: $localize`Resize volume`,
          refreshAfterExecute: true,
          callback: () => this.matDialog.open(
            ResizeDatabaseInstanceVolumeDialogComponent, {
              data: {
                database_instance: this.object
              },
              autoFocus: false,
            }).afterClosed().pipe(map(result => ({message: result} as IActionResult))),
          noPermissions: !this.permissions['dbaas-instances.resize_volume'],
        }
      ));

      actions.push(new RouterLinkAction({
        name: $localize`Resize flavor`,
        tooltip: $localize`Resize flavor`,
        icon: {name: 'resize', class: 'fl-icons'},
        router: this.router,
        routerUrl: this.config.getPanelUrl(`openstack/database-instances/${this.object.id}/resize`),
        noPermissions: !this.permissions['dbaas-instances.resize_flavor'],
      }));

      actions.push(new CallbackAction(
        {
          object: this.object,
          icon: {name: 'edit', class: 'fl-icons'},
          tooltip: $localize`Rename`,
          name: $localize`Rename`,
          refreshAfterExecute: true,
          callback: () => this.matDialog.open(
            RenameDatabaseInstanceDialogComponent, {
              data: {
                database_instance: this.object
              },
              autoFocus: false,
            }).afterClosed().pipe(map(result => ({message: result} as IActionResult))),
          noPermissions: !this.permissions['dbaas-instances.rename'],
        }
      ));
    }

    actions.push(new ApiCallAction(
      {
        object: this.object,
        icon: {name: 'delete'},
        name: $localize`Delete`,
        tooltip: $localize`Delete database instance`,
        confirmOptions: {
          confirm: true,
          title: $localize`Delete database instance`,
          message: $localize`Are you sure you want to delete database instance ${this.object.name || this.object.id}?`,
        },
        successMessage: $localize`Database instance delete queued`,
        apiService: this.dbaasInstancesApiService,
        callType: CallType.Delete,
        refreshAfterExecute: false,
        redirectAfterExecute: true,
        redirectUrl: this.config.getPanelUrl('openstack/database-instances'),
        redirectQueryParams: this.orderingService.getQueryParams('openstack/database-instances'),
        noPermissions: !this.permissions['dbaas-instances.destroy'],
        disabled: this.object.status === 'BUILD',
      }
    ));

    return actions;
  }

  getDetailsActions(): IAction[] {
    const actions = [];

    switch (this.state) {
      case 'create':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/database-instances`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Create`}));
        break;
      case 'edit':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/database-instances`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Save`}));
        break;
      case 'resize':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/database-instances`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Resize`}));
        break;
      default:
        break;
    }

    return actions;
  }

  getDetailsLink(): string {
    return this.config.getPanelUrl(`openstack/database-instances/${this.object.id}`);
  }

  getCardFields(): IDataField[] {
    let databaseInstanceCardFirstField = '';
    if (this.object?.addresses?.length && this.object.addresses[0].address) {
      if (this.object.flavor) {
        databaseInstanceCardFirstField = $localize`${this.object.addresses[0].address}, ${this.object.flavor.name}`;
      } else {
        databaseInstanceCardFirstField = `${this.object.addresses[0].address}`;
      }
    } else if (this.object.flavor) {
      databaseInstanceCardFirstField = this.object.flavor?.name;
    }
    if (databaseInstanceCardFirstField) {
      databaseInstanceCardFirstField = `${databaseInstanceCardFirstField}, ${this.object.region}`;
    } else {
      databaseInstanceCardFirstField = this.object.region;
    }
    const fields = [
      {
        value: databaseInstanceCardFirstField,
      },
    ] as Array<IDataField>;
    if (this.object.replica_of) {
      fields.push({
        name: $localize`Replica of`,
        value: this.object.replica_of.name,
        url: this.config.getPanelUrl(`openstack/database-instances/${this.object?.replica_of.id}`)
      });
    }
    fields.push.apply(fields, [
      {
        name: $localize`Created on`,
        value: `${this.datePipe.transform(this.object.created)}`,
        title: `${this.datePipe.getTitleAttributeValue(this.object.created)}`
      },
      {
        name: $localize`Client`,
        value: this.object.client ? this.object.client.display : $localize`n/a`,
      }
    ]);
    return fields;
  }


  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'create':
        return [
          {
            tabName: $localize`Create`,
            tabIdentifier: 'create',
            component: DbaasInstanceCreateFormComponent,
          }
        ];
      case 'details':
        const tabs: IDetailsTab[] = [
          {
            tabName: $localize`Overview`,
            tabIdentifier: 'overview',
            component: DbaasInstanceOverviewTabComponent,
          },
        ];
        if (this.object?.datastore?.type === 'mysql' && this.object.status !== 'ERROR') {
          // only mysql can manage users/databases through trove API
          tabs.push({
            tabName: $localize`Users`,
            tabIdentifier: 'users',
            component: DbaasInstanceUsersTabComponent,
          });
          tabs.push({
            tabName: $localize`Databases`,
            tabIdentifier: 'databases',
            component: DbaasInstanceDatabasesTabComponent,
          });
          tabs.push({
            tabName: $localize`Root access`,
            tabIdentifier: 'root-access',
            component: DbaasInstanceRootUserTabComponent,
            featureName: 'openstack.dbaas.manage-root-access',
          });
        }

        tabs.push({
          tabName: $localize`Backups`,
          tabIdentifier: 'backups',
          component: DbaasInstanceBackupsTabComponent,
          featureName: 'openstack.dbaas.backups',
        });

        tabs.push({
          tabName: $localize`Backup schedules`,
          tabIdentifier: 'backup-schedules',
          component: DbaasInstanceBackupSchedulesComponent,
          featureName: 'openstack.dbaas.backup-schedules',
        });

        tabs.push({
          tabName: $localize`Audit log`,
          tabIdentifier: 'audit-log',
          component: EntityAuditLogComponent,
          featureName: 'utils.activitylog',
          data: {
            entity_type: 'dbaas_instance'
          }
        });

        return tabs;
      case 'resize':
        return [
          {
            tabName: $localize`Resize flavor`,
            tabIdentifier: 'resize-flavor',
            component: DbaasInstanceResizeFlavorFormComponent,
          }
        ];
      case 'edit':
        return [];
    }
  }

  getCardTags(): string[] {
    const tags = [];
    if (this.object.replicas && this.object.replicas.length) {
      tags.push($localize`has replicas`);
    }
    return tags;
  }

  getObjectDetailsRefreshInterval(): number {
    switch (this.state) {
      case 'details':
        return this.config.getDefaultRefreshInterval(true);
      default:
        return null;
    }
  }
}
