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 { INetworkModel } from '@fleio-api/openstack/model/network.model';
import { NetworksApiService } from '@fleio-api/openstack/network/networks-api.service';
import { NetworkEditFormComponent } from './tabs/network-edit-form/network-edit-form.component';
import { ISubnetModel } from '@fleio-api/openstack/model/subnet.model';
import { NetworkDetailsOverviewComponent } from '@shared/common-tabs/openstack/networks/network-details-overview/network-details-overview.component';
import { NetworkEditSubnetFormComponent } from '@shared/common-tabs/openstack/networks/network-edit-subnet-form/network-edit-subnet-form.component';
import { NetworkAutoCreateFormComponent } from '@shared/common-tabs/openstack/networks/network-auto-create-form/network-auto-create-form.component';

export class NetworkUiService extends ObjectUIServiceBase<INetworkModel> {
  private readonly router: Router;
  private readonly config: ConfigService;
  private readonly networksApiService: NetworksApiService;
  private readonly datePipe: DateFormatterPipe;

  constructor(
    networkModel: INetworkModel, permissions: IPermissionsModel, state: string,
    router: Router, config: ConfigService, networksApiService: NetworksApiService
  ) {
    super(networkModel, permissions, state);
    this.router = router;
    this.config = config;
    this.networksApiService = networksApiService;
    this.datePipe = new DateFormatterPipe(this.config);
  }

  getIcon(): IIcon {
    return null;
  }

  getStatus(): IObjectStatus {
    return null;
  }

  getTitle(additionalObjects?: { subnet: ISubnetModel }): ITitle {
    let subText: string;
    if (this.object.router_external) {
      subText = $localize`EXTERNAL`;
    } else {
      subText = $localize`INTERNAL`;
    }
    switch (this.state) {
      case 'edit':
        return {
          text: $localize`Edit network ${this.object.name}`,
          subText,
        };

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

      case 'auto-create':
        return {
          text: $localize`Get me a network`,
        };

      case 'config-auto-create':
        return {
          text: $localize`Config auto create options`,
        };

      case 'add-subnet':
        return {
          text: $localize`Add a new subnet to network ${this.object.name}`,
        };

      case 'edit-subnet':
        return {
          text: $localize`Edit subnet ${additionalObjects.subnet.name} of network ${this.object.name}`,
        };

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

  private networkAllowedAction(action: string) {
    return this.object.allowed_actions.indexOf(action) > -1;
  }

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

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

    if (this.networkAllowedAction('add_subnet')) {
      actions.push(new RouterLinkAction({
          icon: {name: 'playlist_add'},
          name: $localize`Add subnet`,
          tooltip: $localize`Add subnet`,
          routerUrl: this.config.getPanelUrl(`openstack/networks/${this.object.id}/add-subnet`),
          router: this.router,
        }
      ));
    }

    const deleteAction = new ApiCallAction(
      {
        object: this.object,
        icon: {name: 'delete'},
        tooltip: $localize`Delete network`,
        name: $localize`Delete`,
        confirmOptions: {
          confirm: true,
          title: $localize`Delete network`,
          message: $localize`Are you sure you want to delete network ${this.object.name}?`,
        },
        successMessage: $localize`Network delete queued`,
        apiService: this.networksApiService,
        callType: CallType.Delete,
        refreshAfterExecute: false,
        redirectAfterExecute: true,
        redirectUrl: this.config.getPanelUrl('openstack/networks'),
        noPermissions: !this.permissions['networks.destroy'],
      }
    );

    if (this.networkAllowedAction('delete')) {
      actions.push(deleteAction);
    }

    return actions;
  }

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

    switch (this.state) {
      case 'config-auto-create':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/networks`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Apply & recheck configuration`}));
        break;
      case 'auto-create':
      case 'create':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/networks`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Create`}));
        break;
      case 'add-subnet':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/networks`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Add subnet`}));
        break;
      case 'edit-subnet':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/networks`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Save subnet`}));
        break;
      case 'edit':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/networks`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Save`}));
        break;
      default:
        break;
    }

    return actions;
  }

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

  getCardFields(): IDataField[] {
    let availabilityZones = '';
    if (this.object.extra && typeof this.object.extra === 'object' &&
      this.object.extra.hasOwnProperty('availability_zones') &&
      Array.isArray(this.object.extra.availability_zones)) {
      for (const az of this.object.extra.availability_zones) {
        if (availabilityZones !== '') {
          availabilityZones += ', ';
        }
        availabilityZones += az;
      }
    }
    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},
    ];
    if (availabilityZones) {
      fields.push({name: $localize`Availability zones`, value: availabilityZones},);
    }

    return fields;
  }

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'auto-create':
        return [
          {
            tabName: $localize`Create`,
            tabIdentifier: 'create',
            component: NetworkAutoCreateFormComponent,
          },
        ];
      case 'create':
        return [
          {
            tabName: $localize`Create`,
            tabIdentifier: 'create',
            component: NetworkEditFormComponent,
          },
        ];
      case 'details':
        return [
          {
            tabName: $localize`Overview`,
            tabIdentifier: 'overview',
            component: NetworkDetailsOverviewComponent,
          },
        ];
      case 'add-subnet':
        return [
          {
            tabName: $localize`Add interface`,
            tabIdentifier: 'add-interface',
            component: NetworkEditSubnetFormComponent,
          },
        ];
      case 'edit':
        return [
          {
            tabName: $localize`Edit`,
            tabIdentifier: 'edit',
            component: NetworkEditFormComponent,
          },
        ];
      case 'edit-subnet':
        return [
          {
            tabName: $localize`Edit interface`,
            tabIdentifier: 'edit-interface',
            component: NetworkEditSubnetFormComponent,
          },
        ];
    }
  }

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

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