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 { IClusterTemplateModel } from '@fleio-api/openstack/model/cluster-template.model';
import { ClusterTemplatesApiService } from '@fleio-api/openstack/cluster-template/cluster-templates-api.service';
import { ClusterTemplateDetailsInfoComponent } from '@shared/common-tabs/openstack/cluster-templates/cluster-template-details-info/cluster-template-details-info.component';
import { ClusterTemplateDetailsNodeSpecComponent } from '@shared/common-tabs/openstack/cluster-templates/cluster-template-details-node-spec/cluster-template-details-node-spec.component';
import { ClusterTemplateDetailsNetworkComponent } from '@shared/common-tabs/openstack/cluster-templates/cluster-template-details-network/cluster-template-details-network.component';
import { ClusterTemplateDetailsLabelsComponent } from '@shared/common-tabs/openstack/cluster-templates/cluster-template-details-labels/cluster-template-details-labels.component';
import { ClusterTemplateEditFormComponent } from '@shared/common-tabs/openstack/cluster-templates/cluster-template-edit-form/cluster-template-edit-form.component';
import { ClusterDetailsAssignedFlavorsComponent } from './tabs/cluster-details-assigned-flavors/cluster-details-assigned-flavors.component';
import { EntityAuditLogComponent } from '../../common-components/entity-audit-log/entity-audit-log.component';

export class ClusterTemplateUiService extends ObjectUIServiceBase<IClusterTemplateModel> {
  private readonly router: Router;
  private readonly config: ConfigService;
  private readonly clusterTemplatesApiService: ClusterTemplatesApiService;
  private readonly datePipe: DateFormatterPipe;

  constructor(
    object: IClusterTemplateModel, permissions: IPermissionsModel, state: string,
    router: Router, config: ConfigService, clusterTemplatesApiService: ClusterTemplatesApiService,
  ) {
    super(object, permissions, state);
    this.router = router;
    this.config = config;
    this.clusterTemplatesApiService = clusterTemplatesApiService;
    this.datePipe = new DateFormatterPipe(this.config);
  }

  getIcon(): IIcon {
    return null;
  }

  getStatus(): IObjectStatus {
    if (this.object.client) {
      // template can be used by client
      return {type: StatusType.Defined, value: StatusValue.Enabled};
    }
    if (this.object.hidden || !this.object.public) {
      // template cannot be used by any client
      return {type: StatusType.Defined, value: StatusValue.Disabled};
    }
    return {type: StatusType.Defined, value: StatusValue.Enabled};
  }

  getTitle(): ITitle {
    switch (this.state) {
      case 'create':
        return {
          text: $localize`Create cluster template`
        };
      case 'edit':
        return {
          text: $localize`Edit cluster template ${this.object.name}`,
        };
      case 'details':
        return {
          text: this.object.name,
        };
      default:
        return {
          text: this.object.name,
          subText: this.object.id.toString(),
        };
    }
  }

  getActions(): IAction[] {
    return [
      new RouterLinkAction({
          icon: {name: 'edit', class: 'fl-icons'},
          name: $localize`Edit`,
          tooltip: $localize`Edit cluster template`,
          routerUrl: this.config.getPanelUrl(`openstack/cluster-templates/${this.object.id}/edit`),
          router: this.router,
          noPermissions: !this.permissions['clustertemplates.update'],
        }
      ),

      new ApiCallAction({
        object: this.object,
        icon: {name: 'delete'},
        tooltip: $localize`Delete cluster template`,
        name: $localize`Delete`,
        confirmOptions: {
          confirm: true,
          title: $localize`Delete cluster template`,
          message: $localize`Are you sure?`,
        },
        successMessage: $localize`Cluster template delete queued`,
        errorMessage: $localize`Failed to delete cluster template, check logs for details`,
        apiService: this.clusterTemplatesApiService,
        callType: CallType.Delete,
        refreshAfterExecute: false,
        redirectAfterExecute: true,
        redirectUrl: this.config.getPanelUrl('openstack/cluster-templates'),
        noPermissions: !this.permissions['clustertemplates.destroy'],
      })
    ];
  }

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

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

    return actions;
  }

  getDetailsLink(): string {
    return this.config.getPanelUrl(`openstack/cluster-templates/${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`Region`,
        value: this.object.region,
      },
    ] as Array<IDataField>;
    if (this.object.client) {
      fields.push({
        name: $localize`Client`,
        value: this.object.client.display
      });
    }
    return fields;
  }

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'details':
        return [
          {
            tabName: $localize`Info`,
            tabIdentifier: 'info',
            component: ClusterTemplateDetailsInfoComponent
          },
          {
            tabName: $localize`Node spec`,
            tabIdentifier: 'node-spec',
            component: ClusterTemplateDetailsNodeSpecComponent,
          },
          {
            tabName: $localize`Network`,
            tabIdentifier: 'network',
            component: ClusterTemplateDetailsNetworkComponent,
          },
          {
            tabName: $localize`Labels`,
            tabIdentifier: 'labels',
            component: ClusterTemplateDetailsLabelsComponent,
          },
          {
            tabName: $localize`Assigned flavors`,
            tabIdentifier: 'assigned-flavors',
            component: ClusterDetailsAssignedFlavorsComponent,
            featureName: 'openstack.flavors'
          },
          {
            tabName: $localize`Audit log`,
            tabIdentifier: 'audit-log',
            component: EntityAuditLogComponent,
            featureName: 'utils.activitylog',
            data: {
              entity_type: 'cluster_template'
            }
          }
        ];
      case 'create':
        return [
          {
            tabName: $localize`Create`,
            tabIdentifier: 'create',
            component: ClusterTemplateEditFormComponent,
          }
        ];
      case 'edit':
        return [
          {
            tabName: $localize`Edit`,
            tabIdentifier: 'edit',
            component: ClusterTemplateEditFormComponent,
          }
        ];
      default:
        return [];
    }
  }

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