import { IPermissionsModel } from '@fleio-api/base-model/IPermissionsModel';
import { ITitle } from '@objects-view/interfaces/card-data/card-title';
import { IObjectStatus, StatusType, StatusValue } from '@objects-view/interfaces/object-status';
import { ObjectUIServiceBase } from '@objects-view/object-ui-service-base';
import { IAction } from '@objects-view/interfaces/actions/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 { IHeatStackModel } from '@fleio-api/openstack/orchestration/model/heat-stack.model';
import { HeatStacksApiService } from '@fleio-api/openstack/orchestration/heat-stacks/heat-stacks-api.service';
import { HeatStackDetailsOverviewComponent } from './tabs/heat-stack-details-overview/heat-stack-details-overview.component';
import { HeatStackEditFormComponent } from './tabs/heat-stack-edit-form/heat-stack-edit-form.component';
import { FormatHelper } from '@shared/ui-api/helpers/format-helper';
import { HeatStackDetailsResourcesComponent } from './tabs/heat-stack-details-resources/heat-stack-details-resources.component';
import { HeatStackDetailsEventsComponent } from './tabs/heat-stack-details-events/heat-stack-details-events.component';
import { HeatStackDetailsTemplateComponent } from './tabs/heat-stack-details-template/heat-stack-details-template.component';
import { RouterLinkAction } from '@objects-view/actions/router-link-action';
import { CallbackAction } from '@objects-view/actions/callback-action';
import { IIcon } from '@shared/ui/common/interfaces/icon';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';

export class HeatStackUiService extends ObjectUIServiceBase<IHeatStackModel> {
  private readonly router: Router;
  private readonly config: ConfigService;
  private readonly heatStacksApiService: HeatStacksApiService;
  private readonly datePipe: DateFormatterPipe;
  private readonly formatHelper: FormatHelper;


  constructor(
    heatStackModel: IHeatStackModel, permissions: IPermissionsModel, state: string,
    router: Router, config: ConfigService, heatStacksApiService: HeatStacksApiService
  ) {
    super(heatStackModel, permissions, state);
    this.router = router;
    this.config = config;
    this.heatStacksApiService = heatStacksApiService;
    this.datePipe = new DateFormatterPipe(this.config);
    this.formatHelper = new FormatHelper();
  }

  getIcon(): IIcon {
    return null;
  }

  getStatus(): IObjectStatus {
    if (!this.object?.stack_status) {
      return null;
    }

    const baseStatus = this.object.stack_status.split('_')[0];
    const errorStatus = this.object.stack_status.split('_').slice(1).join('_');

    switch (errorStatus) {
      case 'IN_PROGRESS':
        return {type: StatusType.Changing, value: StatusValue.Pending};
      case 'COMPLETE':
        if (baseStatus === 'SUSPEND') {
          return {type: StatusType.Defined, value: StatusValue.Suspended};
        } else {
          return {type: StatusType.Defined, value: StatusValue.Success};
        }
      case 'FAILED':
        return {type: StatusType.Defined, value: StatusValue.Failed};
      default:
        return {type: StatusType.None, value: StatusValue.None};
    }
  }

  getTitle(): ITitle {
    switch (this.state) {
      case 'create':
        return {
          text: $localize`Create heat stack`,
        };
      case 'preview':
        return {
          text: $localize`Preview heat stack`,
        };
      case 'change-template':
        return {
          text: $localize`Change stack template for ${this.object.stack_name}`,
        };
      case 'details':
      default:
        return {
          text: `${this.object.stack_name || this.object.id}`,
          subText: this.formatHelper.formatStatus(this.object.stack_status),
        };
    }
  }

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

    actions.push(new RouterLinkAction({
        icon: {name: 'edit', class: 'fl-icons'},
        name: $localize`Change template`,
        tooltip: $localize`Change template`,
        routerUrl: this.config.getPanelUrl(`openstack/heat-stacks/${this.object.id}/change-template`),
        router: this.router,
      }
    ));

    actions.push(new ApiCallAction(
      {
        object: this.object,
        icon: {name: 'pause'},
        tooltip: $localize`Suspend stack`,
        name: $localize`Suspend`,
        confirmOptions: {
          confirm: true,
          title: $localize`Suspend stack`,
          message: $localize`Are you sure you want to suspend stack "${this.object.stack_name}"?`
        },
        apiService: this.heatStacksApiService,
        apiAction: 'suspend',
      }
    ));

    actions.push(new ApiCallAction(
      {
        object: this.object,
        icon: {name: 'play_arrow'},
        tooltip: $localize`Resume stack`,
        name: $localize`Resume`,
        confirmOptions: {
          confirm: true,
          title: $localize`Resume stack`,
          message: $localize`Are you sure you want to resume stack "${this.object.stack_name}"?`
        },
        apiService: this.heatStacksApiService,
        apiAction: 'resume',
      }
    ));

    actions.push(new ApiCallAction(
      {
        object: this.object,
        icon: {name: 'check'},
        tooltip: $localize`Check stack`,
        name: $localize`Check`,
        confirmOptions: {
          confirm: true,
          title: $localize`Check stack`,
          message: $localize`Are you sure you want to check stack "${this.object.stack_name}"?`
        },
        apiService: this.heatStacksApiService,
        apiAction: 'check',
      }
    ));

    actions.push(new ApiCallAction(
      {
        object: this.object,
        icon: {name: 'delete'},
        name: $localize`Delete`,
        tooltip: $localize`Delete heat stack`,
        confirmOptions: {
          confirm: true,
          title: $localize`Delete heat stack`,
          message: $localize`Are you sure you want to delete heat stack "${this.object.stack_name}"?`,
        },
        successMessage: $localize`Heat stack delete queued`,
        errorMessage: $localize`Failed to delete heat stack, please contact support`,
        apiService: this.heatStacksApiService,
        callType: CallType.Delete,
        refreshAfterExecute: false,
        redirectAfterExecute: true,
        redirectUrl: this.config.getPanelUrl('openstack/heat-stacks'),
      }
    ));

    return actions;
  }

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

    switch (this.state) {
      case 'create':
      case 'preview':
      case 'change-template':
        actions.push(new RouterLinkAction({
          name: $localize`Cancel`,
          routerUrl: this.config.getPrevUrl(`openstack/heat-stacks`),
          router: this.router,
        }));
        actions.push(new CallbackAction({name: $localize`Next`}));
        break;
      default:
        break;
    }

    return actions;
  }

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

  getCardFields(): IDataField[] {
    const fields = [];

    fields.push({
      name: $localize`Created`,
      value: this.datePipe.transform(this.object.created_at),
      title: this.datePipe.getTitleAttributeValue(this.object.created_at),
    });

    fields.push({
      name: $localize`Updated`,
      value: this.object.updated_time ? this.datePipe.transform(this.object.updated_time) : $localize`n/a`,
      title: this.object.updated_time ? this.datePipe.getTitleAttributeValue(this.object.updated_time) : $localize`n/a`,
    });

    return fields;
  }

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'details':
        return [
          {
            tabName: $localize`Overview`,
            tabIdentifier: 'overview',
            component: HeatStackDetailsOverviewComponent,
          },
          {
            tabName: $localize`Resources`,
            tabIdentifier: 'resources',
            component: HeatStackDetailsResourcesComponent,
          },
          {
            tabName: $localize`Events`,
            tabIdentifier: 'events',
            component: HeatStackDetailsEventsComponent,
          },
          {
            tabName: $localize`Template`,
            tabIdentifier: 'template',
            component: HeatStackDetailsTemplateComponent,
          },
        ];
      case 'create':
        return [
          {
            tabName: $localize`Create`,
            tabIdentifier: 'create',
            component: HeatStackEditFormComponent,
          },
        ];
      case 'preview':
        return [
          {
            tabName: $localize`Create`,
            tabIdentifier: 'create',
            component: HeatStackEditFormComponent,
          },
        ];
      case 'change-template':
        return [
          {
            tabName: $localize`Edit heat stack`,
            tabIdentifier: 'edit-heat-stack',
            component: HeatStackEditFormComponent,
          },
        ];
    }
  }

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

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