import { ObjectUIServiceBase } from '@objects-view/object-ui-service-base';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { IPermissionsModel } from '@fleio-api/base-model/IPermissionsModel';
import { IIcon } from '@shared/ui/common/interfaces/icon';
import { IObjectStatus } from '@objects-view/interfaces/object-status';
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 { ApiCallAction, CallType } from '@objects-view/actions/api-call-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 { SecurityGroupsApiService } from '@fleio-api/openstack/security-groups/security-groups-api.service';
import { ISecurityGroupModel } from '@fleio-api/openstack/model/security-group.model';
import { SecurityGroupEditFormComponent } from '@shared/common-tabs/openstack/security-groups/security-group-create-form/security-group-edit-form.component';
import { SecurityGroupsDetailsOverviewComponent } from '@shared/common-tabs/openstack/security-groups/security-groups-details-overview/security-groups-details-overview.component';
import { SecurityGroupAddRuleFormComponent } from '@shared/common-tabs/openstack/security-groups/security-group-add-rule-form/security-group-add-rule-form.component';
import { EntityAuditLogComponent } from '../../common-components/entity-audit-log/entity-audit-log.component';

export class SecurityGroupsUiService extends ObjectUIServiceBase<ISecurityGroupModel> {
  private readonly router: Router;
  private readonly config: ConfigService;
  private readonly securityGroupsApiService: SecurityGroupsApiService;

  constructor(
    object: ISecurityGroupModel, permissions: IPermissionsModel, state: string,
    router: Router, config: ConfigService, securityGroupsApiService: SecurityGroupsApiService,
  ) {
    super(object, permissions, state);
    this.router = router;
    this.config = config;
    this.securityGroupsApiService = securityGroupsApiService;
  }

  getIcon(): IIcon {
    return null;
  }

  getStatus(): IObjectStatus {
    return null;
  }

  getTitle(): ITitle {
    switch (this.state) {
      case 'edit':
        return {
          text: $localize`Edit security group ${this.object.name || this.object.id}`,
        };

      case 'add-rule':
        return {
          text: $localize`Add rule for ${this.object.name || this.object.id}`,
        };

      case 'create':
        return {
          text: $localize`Create security group`,
        };

      default:
        return {
          text: `${this.object.name || this.object.id}`,
          subText: this.object.description
        };
    }
  }

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

    actions.push(new RouterLinkAction({
        icon: {name: 'edit', class: 'fl-icons'},
        name: $localize`Edit`,
        tooltip: $localize`Edit security group`,
        routerUrl: this.config.getPanelUrl(`openstack/security-groups/${this.object.id}/edit`),
        router: this.router,
        noPermissions: !this.permissions['securitygroups.update'],
      }
    ));

    actions.push(new RouterLinkAction({
        icon: {name: 'playlist_add'},
        name: $localize`Add rule`,
        tooltip: $localize`Add rule`,
        routerUrl: this.config.getPanelUrl(`openstack/security-groups/${this.object.id}/add-rule`),
        router: this.router,
        noPermissions: !this.permissions['securitygroups.add_rule'],
      }
    ));

    const deleteAction = new ApiCallAction(
      {
        object: this.object,
        icon: {name: 'delete'},
        tooltip: $localize`Delete security group`,
        name: $localize`Delete`,
        confirmOptions: {
          confirm: true,
          title: $localize`Delete security group`,
          message: $localize`Are you sure you want to delete security group ${this.object.name || this.object.id}?`,
        },
        successMessage: $localize`Security group delete queued`,
        errorMessage: $localize`Failed to delete security group, check logs for details`,
        apiService: this.securityGroupsApiService,
        callType: CallType.Delete,
        refreshAfterExecute: false,
        redirectAfterExecute: true,
        redirectUrl: this.config.getPanelUrl('openstack/security-groups'),
        noPermissions: !this.permissions['securitygroups.destroy'],
      }
    );

    actions.push(deleteAction);

    return actions;
  }

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

    switch (this.state) {
      case 'create':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/security-groups`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Create`}));
        break;
      case 'add-rule':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/security-groups/${this.object.id}`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Add rule`}));
        break;
      case 'edit':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/security-groups`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Save`}));
        break;
      default:
        break;
    }

    return actions;
  }

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

  getCardFields(): IDataField[] {
    let instancesText = '';
    for (const instance of this.object.associated_instances) {
      if (instancesText) {
        instancesText += ', ';
      }
      instancesText += (instance.name || instance.id);
    }
    const fields = [
      {name: $localize`Region`, value: this.object.region},
      {name: $localize`Project`, value: this.object.project}
    ] as IDataField[];
    if (instancesText) {
      fields.push({name: $localize`Instances`, value: instancesText});
    }
    return fields;
  }

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'create':
        return [
          {
            tabName: $localize`Create`,
            tabIdentifier: 'create',
            component: SecurityGroupEditFormComponent
          }
        ];
      case 'edit':
        return [
          {
            tabName: $localize`Edit`,
            tabIdentifier: 'edit',
            component: SecurityGroupEditFormComponent
          }
        ];
      case 'add-rule':
        return [
          {
            tabName: $localize`Add rule`,
            tabIdentifier: 'add-rule',
            component: SecurityGroupAddRuleFormComponent,
          }
        ];
      case 'details':
        return [
          {
            tabName: $localize`Overview`,
            tabIdentifier: 'overview',
            component: SecurityGroupsDetailsOverviewComponent,
          },
          {
            tabName: $localize`Audit log`,
            tabIdentifier: 'audit-log',
            component: EntityAuditLogComponent,
            featureName: 'utils.activitylog',
            data: {
              entity_type: 'security_group'
            }
          }
        ];
      default:
        return [];
    }
  }

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

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