import { IPermissionsModel } from '@fleio-api/base-model/IPermissionsModel';
import { IIcon } from '@shared/ui/common/interfaces/icon';
import { ITitle } from '@objects-view/interfaces/card-data/card-title';
import { IObjectStatus } from '@objects-view/interfaces/object-status';
import { ObjectUIServiceBase } from '@objects-view/object-ui-service-base';
import { IAction } from '@objects-view/interfaces/actions/action';
import { RouterLinkAction } from '@objects-view/actions/router-link-action';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { IDataField } from '@objects-view/interfaces/card-data/data-field';
import { ApiCallAction, CallType } from '@objects-view/actions/api-call-action';
import { IDetailsTab } from '@objects-view/interfaces/details/details-tab';
import { CallbackAction } from '@objects-view/actions/callback-action';
import { ApiUsersApiService } from '@fleio-api/openstack/api-user/api-users-api.service';
import { IApiUserModel } from '@fleio-api/openstack/model/api-user.model';
import { map } from 'rxjs/operators';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { MatDialog } from '@angular/material/dialog';
import { ApiUserCreateFormComponent } from '@openstack-api-users-tabs/api-user-create-form/api-user-edit-form.component';
import { ApiUserEditFormComponent } from '@openstack-api-users-tabs/api-user-edit-form/api-user-edit-form.component';
import { ApiUserDetailsOverviewComponent } from '@openstack-api-users-tabs/api-user-details-overview/api-user-details-overview.component';
import { ApiUserDownloadOpenrcComponent } from '@shared/common-dialogs/openstack/api-users/api-user-download-openrc/api-user-download-openrc.component';
import { EntityAuditLogComponent } from '../../common-components/entity-audit-log/entity-audit-log.component';

export class ApiUserUiService extends ObjectUIServiceBase<IApiUserModel> {
  private readonly router: Router;
  private readonly config: ConfigService;
  private readonly apiUsersApi: ApiUsersApiService;
  private readonly matDialog: MatDialog;

  constructor(
    user: IApiUserModel, permissions: IPermissionsModel, state: string,
    router: Router, config: ConfigService, apiUsersApi: ApiUsersApiService, matDialog: MatDialog,
  ) {
    super(user, permissions, state);
    this.matDialog = matDialog;
    this.router = router;
    this.config = config;
    this.apiUsersApi = apiUsersApi;
  }

  getIcon(): IIcon {
    return null;
  }

  getStatus(): IObjectStatus {
    return null;
  }

  getTitle(): ITitle {
    switch (this.state) {
      case 'details':
        return {
          text: $localize`User ${this.object.name}`,
        };

      case 'edit':
        return {
          text: $localize`Edit ${this.object.name}`,
        };

      case 'create':
        return {
          text: $localize`Create API user`,
        };

      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`,
        routerUrl: this.config.getPanelUrl(`openstack/api-users/${this.object.id}/edit`),
        router: this.router,
        noPermissions: !this.permissions['apiusers.update'],
      }
    ));

    actions.push(new CallbackAction(
      {
        object: this.object,
        icon: {name: 'arrow_downward'},
        tooltip: $localize`Get OpenRC file`,
        name: $localize`Get OpenRC file`,
        callback: () => this.matDialog.open(
            ApiUserDownloadOpenrcComponent, {
              data: {apiUser: 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'},
        tooltip: $localize`Delete`,
        name: $localize`Delete`,
        confirmOptions: {
          confirm: true,
          title: $localize`Delete user`,
          message: $localize`Are you sure you want to delete user ${this.object.name}?`
        },
        successMessage: $localize`API user deleted`,
        errorMessage: $localize`Failed to delete API user, check logs for details`,
        apiService: this.apiUsersApi,
        callType: CallType.Delete,
        refreshAfterExecute: false,
        redirectAfterExecute: true,
        redirectUrl: this.config.getPanelUrl('openstack/api-users'),
        noPermissions: !this.permissions['apiusers.destroy'],
      }
    ));

    return actions;
  }

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

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

  getCardFields(): IDataField[] {
    return [
      {
        name: $localize`Id`,
        value: this.object.id as string
      },
      {
        name: $localize`Project`,
        value: this.object.project_name || this.object.default_project_id
      }
    ];
  }

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

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

    switch (this.state) {
      case 'create':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/api-users`),
            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/api-users`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Save`}));
        break;
      default:
        break;
    }

    return actions;
  }
}
