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, 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 { 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 { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';
import { CallbackAction } from '@objects-view/actions/callback-action';
import { MatDialog } from '@angular/material/dialog';
import { ILoadBalancerModel } from '@fleio-api/openstack/load-balancing/model/load-balancer.model';
import { LoadBalancersApiService } from '@fleio-api/openstack/load-balancing/load-balancers/load-balancers-api.service';
import {
  LoadBalancerDetailsOverviewComponent
} from './tabs/load-balancer-details-overview/load-balancer-details-overview.component';
import { LoadBalancerCreateFormComponent } from './tabs/load-balancer-create-form/load-balancer-create-form.component';
import {
  LoadBalancerAssociateFloatingIpFormComponent
} from './tabs/load-balancer-associate-floating-ip-form/load-balancer-associate-floating-ip-form.component';
import { LoadBalancerEditFormComponent } from './tabs/load-balancer-edit-form/load-balancer-edit-form.component';
import {
  LoadBalancerDetailsListenersComponent
} from './tabs/load-balancer-details-listeners/load-balancer-details-listeners.component';
import {
  LoadBalancerDetailsPoolsComponent
} from './tabs/load-balancer-details-pools/load-balancer-details-pools.component';
import { RouteHelper } from '@shared/ui-api/route-helper';
import { IDetailsLink } from '@objects-view/interfaces/details-link';

export class LoadBalancerUiService extends ObjectUIServiceBase<ILoadBalancerModel> {
  private readonly router: Router;
  private readonly config: ConfigService;
  private readonly loadBalancersApiService: LoadBalancersApiService;
  private readonly datePipe: DateFormatterPipe;
  private readonly matDialog: MatDialog;


  constructor(
    loadBalancerModel: ILoadBalancerModel, permissions: IPermissionsModel, state: string,
    router: Router, config: ConfigService, loadBalancersApiService: LoadBalancersApiService,
    matDialog: MatDialog,
  ) {
    super(loadBalancerModel, permissions, state);
    this.matDialog = matDialog;
    this.router = router;
    this.config = config;
    this.loadBalancersApiService = loadBalancersApiService;
    this.datePipe = new DateFormatterPipe(this.config);
  }

  getIcon(): IIcon {
    return null;
  }

  getStatus(): IObjectStatus {
    switch (this.object.operating_status) {
      case 'ONLINE':
        return {type: StatusType.Defined, value: StatusValue.Active};
      case 'DEGRADED':
      case 'DRAINING':
      case 'NO_MONITOR':
        return {type: StatusType.Defined, value: StatusValue.Warning};
      case 'OFFLINE':
      case 'ERROR':
        return {type: StatusType.Defined, value: StatusValue.Error};
      default:
        return {type: StatusType.None, value: StatusValue.None};
    }
  }

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

      case 'create':
        return {
          text: $localize`Create new load balancer`,
        };

      default:
        return {
          text: `${this.object.name || this.object.id}`,
          subText: this.object.operating_status.toLocaleUpperCase(),
        };
    }
  }

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

    actions.push(
      new RouterLinkAction({
          name: $localize`Edit load balancer`,
          tooltip: $localize`Edit load balancers`,
          icon: {name: 'edit'},
          router: this.router,
          routerUrl: this.config.getPanelUrl(`openstack/load-balancers/${this.object.id}/edit`),
          propagateQueryParams: ['region'],
        }
      )
    );

    if (this.object.floating_ip) {
      actions.push(new ApiCallAction(
        {
          object: this.object,
          icon: {name: 'delete_sweep'},
          tooltip: $localize`Dissociate floating IP`,
          name: $localize`Dissociate floating IP`,
          confirmOptions: {
            confirm: true,
            title: $localize`Dissociate floating IP`,
            message: $localize`Are you sure you want to dissociate floating IP from ${this.object.name}?`
          },
          successMessage: $localize`Dissociate floating IP scheduled`,
          errorMessage: $localize`Failed to dissociate floating IP, please contact support`,
          apiService: this.loadBalancersApiService,
          callType: CallType.Post,
          apiAction: 'dissociate-floating-ip',
          refreshAfterExecute: true,
          redirectAfterExecute: false,
          propagateQueryParams: ['region'],
        }
      ));
    } else {
      actions.push(
        new RouterLinkAction({
            name: $localize`Associate floating IP`,
            tooltip: $localize`Associate floating IP`,
            icon: {name: 'playlist_add'},
            router: this.router,
            routerUrl: this.config.getPanelUrl(
              `openstack/load-balancers/${this.object.id}/associate-floating-ip`,
            ),
            propagateQueryParams: ['region'],
          }
        )
      );
    }

    actions.push(new ApiCallAction(
      {
        object: this.object,
        icon: {name: 'delete'},
        tooltip: $localize`Delete load balancer`,
        name: $localize`Delete load balancer`,
        confirmOptions: {
          confirm: true,
          title: $localize`Delete load balancer`,
          message: $localize`Are you sure you want to delete load balancer ${this.object.name}?`
        },
        successMessage: $localize`Load balancer delete scheduled`,
        apiService: this.loadBalancersApiService,
        callType: CallType.Delete,
        refreshAfterExecute: false,
        redirectAfterExecute: true,
        redirectUrl: this.config.getPanelUrl('openstack/load-balancers'),
        propagateQueryParams: ['region'],
      }
    ));

    return actions;
  }

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

    switch (this.state) {
      case 'create':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/load-balancers`),
            router: this.router,
            propagateQueryParams: ['region'],
          }
        ));
        actions.push(new CallbackAction({
          name: $localize`Back`,
          internalName: 'back',
          propagateQueryParams: ['region'],
        }));
        actions.push(new CallbackAction({
          name: $localize`Next`,
          internalName: 'next',
          propagateQueryParams: ['region'],
        }));
        actions.push(new CallbackAction({
          name: $localize`Create load balancer`,
          internalName: 'create',
          propagateQueryParams: ['region'],
        }));
        break;
      case 'associate-floating-ip':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/load-balancers`),
            router: this.router,
            propagateQueryParams: ['region'],
          }
        ));
        actions.push(new CallbackAction({
          name: $localize`Associate`,
          propagateQueryParams: ['region'],
        }));
        break;
      case 'edit':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/load-balancers`),
            router: this.router,
            propagateQueryParams: ['region'],
          }
        ));
        actions.push(new CallbackAction({
          name: $localize`Save`,
          propagateQueryParams: ['region'],
        }));
        break;
      default:
        break;
    }

    return actions;
  }

  getDetailsLink(): IDetailsLink {
    const queryParams = RouteHelper.getQueryParams(this.router, ['region']);
    return {
      enabled: true,
      url: this.config.getPanelUrl(`openstack/load-balancers`, this.object.id),
      queryParams,
    };
  }

  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`Provisioning status`,
        value: this.object.provisioning_status,
      },
      {
        name: $localize`Admin state up`,
        value: this.object.admin_state_up ? $localize`Yes` : $localize`No`,
      },
    ];

    return fields;
  }

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'details':
        return [
          {
            tabName: $localize`Overview`,
            tabIdentifier: 'overview',
            component: LoadBalancerDetailsOverviewComponent,
          },
          {
            tabName: $localize`Listeners`,
            tabIdentifier: 'listeners',
            component: LoadBalancerDetailsListenersComponent,
          },
          {
            tabName: $localize`Pools`,
            tabIdentifier: 'pools',
            component: LoadBalancerDetailsPoolsComponent,
          },
        ];
      case 'create':
        return [
          {
            tabName: $localize`Create`,
            tabIdentifier: 'create',
            component: LoadBalancerCreateFormComponent,
          },
        ];
      case 'edit':
        return [
          {
            tabName: $localize`Edit`,
            tabIdentifier: 'edit',
            component: LoadBalancerEditFormComponent,
          },
        ];
      case 'associate-floating-ip':
        return [
          {
            tabName: $localize`Associate floating IP`,
            tabIdentifier: 'associate-floating-ip',
            component: LoadBalancerAssociateFloatingIpFormComponent,
          },
        ];
    }
  }

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

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