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 { 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 { SshKeyEditFormComponent } from '@shared/common-tabs/openstack/ssh-keys/ssh-key-edit-form/ssh-key-edit-form.component';
import { IPublicKeyModel } from '@fleio-api/public-key/model/public-key.model';
import { PublicKeysApiService } from '@fleio-api/public-key/public-key-api.service';
import {
  SshKeyDetailsOverviewComponent
} from '@shared/common-tabs/openstack/ssh-keys/ssh-key-details-overview/ssh-key-details-overview.component';
import { EntityAuditLogComponent } from '../../common-components/entity-audit-log/entity-audit-log.component';

export class SshKeyUiService extends ObjectUIServiceBase<IPublicKeyModel> {
  private readonly router: Router;
  private readonly config: ConfigService;
  private readonly publicKeysApiService: PublicKeysApiService;
  private readonly datePipe: DateFormatterPipe;

  constructor(
    publicKeyModel: IPublicKeyModel, permissions: IPermissionsModel, state: string,
    router: Router, config: ConfigService, publicKeysApiService: PublicKeysApiService,
  ) {
    super(publicKeyModel, permissions, state);
    this.router = router;
    this.config = config;
    this.publicKeysApiService = publicKeysApiService;
    this.datePipe = new DateFormatterPipe(this.config);
  }

  getIcon(): IIcon {
    return null;
  }

  getStatus(): IObjectStatus {
    return null;
  }

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

      case 'create':
        return {
          text: $localize`Create new SSH key`,
        };

      default:
        return {
          text: `${this.object.name}`,
        };
    }
  }

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

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

    const deleteAction = new ApiCallAction(
      {
        object: this.object,
        icon: {name: 'delete'},
        tooltip: $localize`Delete SSH key`,
        name: $localize`Delete`,
        confirmOptions: {
          confirm: true,
          title: $localize`Delete SSH key`,
          message: $localize`Are you sure you want to delete SSH key ${this.object.name}?`,
        },
        successMessage: $localize`SSH key deleted`,
        errorMessage: $localize`Failed to delete SSH key, check logs for details`,
        apiService: this.publicKeysApiService,
        callType: CallType.Delete,
        refreshAfterExecute: false,
        redirectAfterExecute: true,
        redirectUrl: this.config.getPanelUrl('openstack/ssh-keys'),
        noPermissions: !this.permissions['publickeys.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/ssh-keys`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({
          name: $localize`Generate new key`,
          internalName: 'generateKey'
        }));
        actions.push(new CallbackAction({name: $localize`Save key`}));
        break;
      case 'edit':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/ssh-keys`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Save`}));
        break;
      default:
        break;
    }

    return actions;
  }

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

  getCardFields(): IDataField[] {
    const fields = [
      {
        name: $localize`Created at`,
        value: this.datePipe.transform(this.object.created_at),
        title: this.datePipe.getTitleAttributeValue(this.object.created_at),
      },
      {name: $localize`Fingerprint`, value: this.object.fingerprint},
      {name: $localize`Owner`, value: this.object.user.email, title: this.object.user.display},
    ] as IDataField[];

    return fields;
  }

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

  getCardTags(): string[] {
    const tags = [];
    return tags;
  }
}
