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 { IFloatingIpModel } from '@fleio-api/openstack/floating-ips/model/floating-ip.model';
import { FloatingIpsApiService } from '@fleio-api/openstack/floating-ips/floating-ips-api.service';
import {
  FloatingIpEditFormComponent
} from '@shared/common-tabs/openstack/floating-ips/floating-ip-edit-form/floating-ip-edit-form.component';
import {
  FloatingIpDetailsOverviewComponent
} from '@shared/common-tabs/openstack/floating-ips/floating-ip-details-overview/floating-ip-details-overview.component';
import { map } from 'rxjs/operators';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import {
  FloatingIpSetPtrDialogComponent
} from '@shared/common-dialogs/openstack/floating-ips/floating-ip-set-ptr-dialog/floating-ip-set-ptr-dialog.component';
import { MatDialog } from '@angular/material/dialog';
import { EntityAuditLogComponent } from '../../common-components/entity-audit-log/entity-audit-log.component';

export class FloatingIpUiService extends ObjectUIServiceBase<IFloatingIpModel> {
  private readonly router: Router;
  private readonly config: ConfigService;
  private readonly floatingIpsApiService: FloatingIpsApiService;
  private readonly datePipe: DateFormatterPipe;

  constructor(
    floatingIpModel: IFloatingIpModel, permissions: IPermissionsModel, state: string,
    router: Router, config: ConfigService, floatingIpsApiService: FloatingIpsApiService,
    private readonly matDialog: MatDialog, datePipe: DateFormatterPipe,
  ) {
    super(floatingIpModel, permissions, state);
    this.router = router;
    this.config = config;
    this.datePipe = datePipe;
    this.floatingIpsApiService = floatingIpsApiService;
  }

  getIcon(): IIcon {
    return null;
  }

  getStatus(): IObjectStatus {
    switch (this.object.status) {
      case 'ACTIVE':
        return {type: StatusType.Defined, value: StatusValue.Active};
      case 'DOWN':
        return {type: StatusType.Defined, value: StatusValue.Disabled};
      default:
        return {type: StatusType.None, value: StatusValue.None};
    }
  }

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

      default:
        return {
          text: `${this.object.floating_ip_address || this.object.id.toString()}`,
          subText: this.object.status,
        };
    }
  }

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

    const tooltip = this.object.project ?  $localize`Set PTR`:  $localize`Cannot set PTR on a floating IP not associated with a project`;
    actions.push(new CallbackAction(
      {
        object: this.object,
        icon: {name: 'settings'},
        tooltip,
        name: $localize`Set PTR`,
        disabled: !this.object.project,
        callback: () => this.matDialog.open(
          FloatingIpSetPtrDialogComponent, {
            data: {floatingIp: this.object},
            autoFocus: false,
          }).afterClosed().pipe(map(result => {
          if (result === false) {
            return;
          }
          return {message: result} as IActionResult;
        }))
      }
    ));

    actions.push(new ApiCallAction(
      {
        object: this.object,
        icon: {name: 'delete'},
        name: $localize`Delete`,
        tooltip: $localize`Delete floating ip`,
        confirmOptions: {
          confirm: true,
          title: $localize`Delete floating IP`,
          message: $localize`Are you sure you want to delete floating IP ${this.object.floating_ip_address || this.object.id}?`,
        },
        successMessage: $localize`Floating IP delete queued`,
        errorMessage: $localize`Failed to delete floating IP, check logs for details`,
        apiService: this.floatingIpsApiService,
        callType: CallType.Delete,
        refreshAfterExecute: false,
        redirectAfterExecute: true,
        redirectUrl: this.config.getPanelUrl('openstack/floating-ips'),
        noPermissions: !this.permissions['floatingips.destroy'],
      }
    ));

    return actions;
  }

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

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

    return actions;
  }

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

  getCardFields(): IDataField[] {
    let associatedObjectUrl = null;
    if (this.object.associated_object?.device_type === 'instance') {
      associatedObjectUrl = this.config.getPanelUrl(
        `openstack/instances/${this.object.associated_object.id}`
      );
    }
    return [
      {
        value: $localize`${this.object.floating_network.region}, ${this.object.floating_network.name}`,
        title: $localize`Region: ${this.object.floating_network.region}, network: ${this.object.floating_network.name}`,
      },
      {
        name: $localize`Associated object`,
        value: this.object.associated_object?.name || this.object.associated_object?.id || $localize`n/a`,
        url: associatedObjectUrl
      },
      {
        name: $localize`Created at`,
        value: this.datePipe.transform(this.object.created_at),
        title: this.datePipe.getTitleAttributeValue(this.object.created_at),
      }
    ] as IDataField[];
  }

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'create':
        return [
          {
            tabName: $localize`Create`,
            tabIdentifier: 'create',
            component: FloatingIpEditFormComponent,
          },
        ];
      case 'details':
        return [
          {
            tabName: $localize`Overview`,
            tabIdentifier: 'overview',
            component: FloatingIpDetailsOverviewComponent,
          },
          {
            tabName: $localize`Audit log`,
            tabIdentifier: 'audit-log',
            component: EntityAuditLogComponent,
            featureName: 'utils.activitylog',
            data: {
              entity_type: 'floating_ip'
            }
          }
        ];
    }
  }

  getCardTags(): string[] {
    return [];
  }
}
