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 { CallbackAction } from '@objects-view/actions/callback-action';
import { ImagesApiService } from '@fleio-api/openstack/image/image-api.service';
import { IImageModel } from '@fleio-api/openstack/model/image.model';
import { ImageDetailsOverviewComponent } from '@openstack-images-tabs/image-details-overview/image-details-overview.component';
import { ImageEditFormComponent } from '@openstack-images-tabs/image-edit-form/image-edit-form.component';
import { ImageEditPropertiesFormComponent } from '@openstack-images-tabs/image-edit-properties-form/image-edit-properties-form.component';
import { of } from 'rxjs';
import { ImageCopyDialogComponent } from '@shared/common-dialogs/openstack/images/image-copy-dialog/image-copy-dialog';
import { map } from 'rxjs/operators';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { MatDialog } from '@angular/material/dialog';
import { DateFormatterPipe } from '@shared/ui/common/pipes/date-formatter.pipe';

export class ImageUiService extends ObjectUIServiceBase<IImageModel> {
  private readonly router: Router;
  private readonly config: ConfigService;
  private readonly imagesApiService: ImagesApiService;
  private readonly datePipe: DateFormatterPipe;
  private readonly matDialog: MatDialog;


  constructor(
    image: IImageModel, permissions: IPermissionsModel, state: string,
    router: Router, config: ConfigService, imagesApiService: ImagesApiService, matDialog: MatDialog,
  ) {
    super(image, permissions, state);
    this.router = router;
    this.config = config;
    this.imagesApiService = imagesApiService;
    this.datePipe = new DateFormatterPipe(this.config);
    this.matDialog = matDialog;
  }

  getIcon(): IIcon {
    if (this.state === 'create') {
      return null;
    }
    return {
      class: 'fl-icons',
      name: (this.object.os_distro || 'otheros').split('-').pop(),
    };
  }

  getStatus(): IObjectStatus {
    switch (this.object.status) {
      case 'queued':
      case 'saving':
      case 'pending_delete':
        return {
          type: StatusType.Changing,
          value: StatusValue.Pending,
        };
      case 'killed':
        return {
          type: StatusType.Defined,
          value: StatusValue.Error,
        };
      case 'deleted':
        return {
          type: StatusType.Defined,
          value: StatusValue.Deleted,
        };
      case 'deactivated':
        return {
          type: StatusType.Defined,
          value: StatusValue.Deactivated,
        };
      case 'active':
      default:
        return {
          type: StatusType.Defined,
          value: StatusValue.Active,
        };
    }
  }

  getTitle(): ITitle {
    let prefix = '';
    if (this.object.type === 'snapshot') {
      prefix = $localize`snapshot`;
    }

    if (this.object.disk_format === 'iso') {
      prefix = $localize`ISO`;
    }

    if (prefix.length > 0) {
      prefix = $localize`[${prefix}] `;
    }

    switch (this.state) {
      case 'edit':
        return {
          text: $localize`Edit ${this.object.name || this.object.id}`,
          subText: this.object.status ? this.object.status.toLocaleUpperCase() : $localize`n/a`,
        };

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

      case 'details':
      default:
        return {
          text: `${prefix}${this.object.name || this.object.id}`,
          subText: this.object.status ? this.object.status.toLocaleUpperCase() : $localize`n/a`,
        };
    }
  }

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

    actions.push(new RouterLinkAction({
        icon: {name: 'launch', class: 'fl-icons'},
        name: $localize`Launch`,
        tooltip: $localize`Launch image`,
        routerUrl: this.config.getPanelUrl(
          `openstack/instances/create?image_id=${this.object.id}&region=${this.object.region}`,
        ),
        router: this.router,
      }
    ));

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

    actions.push(new CallbackAction(
      {
        object: this.object,
        tooltip: $localize`Download image`,
        icon: {name: 'cloud_download'},
        name: $localize`Download image`,
        callback: () => {
          this.config.authService.generateOtpToken().subscribe(token => {
            const url = this.config.getPanelApiUrl(
              `openstack/images/${this.object.id}/download?fleio-token=${token}`,
            );
            window.location.href = url;
          });
          return of(null);
        },
        noPermissions: !this.permissions['images.download'],
        disabled: ['queued', 'saving'].includes(this.object.status),
      }
    ));

    actions.push(
      new CallbackAction({
        object: this.object,
        tooltip: $localize`Copy image`,
        icon: {name: 'file_copy'},
        name: $localize`Copy image`,
        featureName: 'openstack.images.copy',
        callback: action => this.matDialog.open(
            ImageCopyDialogComponent, {
              data: {
                image: this.object,
              },
              autoFocus: false,
            }).afterClosed().pipe(map(result => {
            if (result === 'true' || result === true) {
              this.router.navigateByUrl(
                this.config.getPanelUrl(`openstack/images`)
              ).catch();
            }
            return {message: result} as IActionResult;
          }))
      }),
    );

    actions.push(new ApiCallAction(
      {
        object: this.object,
        icon: {name: 'delete'},
        name: $localize`Delete`,
        tooltip: $localize`Delete image`,
        confirmOptions: {
          confirm: true,
          title: $localize`Delete image`,
          message: $localize`Are you sure you want to delete image ${this.object.name}?`,
        },
        successMessage: $localize`Image delete queued`,
        apiService: this.imagesApiService,
        callType: CallType.Delete,
        refreshAfterExecute: false,
        redirectAfterExecute: true,
        redirectUrl: this.config.getPanelUrl('openstack/images'),
        noPermissions: !this.permissions['images.destroy'],
      }
    ));

    return actions;
  }

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

    switch (this.state) {
      case 'create':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/images`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Create image`}));
        break;
      case 'edit':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/images/${this.object.id}`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Update image`}));
        break;
      default:
        break;
    }

    return actions;
  }

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

  getCardFields(): IDataField[] {
    const fields = [];
    fields.push({
      value: $localize`${this.object.min_disk} GB min. disk, ${this.object.region}`
    });

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

    return fields;
  }

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'details':
        return [
          {
            tabName: $localize`Overview`,
            tabIdentifier: 'overview',
            component: ImageDetailsOverviewComponent,
          },
        ];
      case 'create':
        return [
          {
            tabName: $localize`Create`,
            tabIdentifier: 'create',
            component: ImageEditFormComponent,
          },
        ];
      case 'edit':
        return [
          {
            tabName: $localize`Edit image`,
            tabIdentifier: 'edit-image',
            component: ImageEditFormComponent,
          },
          {
            tabName: $localize`Properties`,
            tabIdentifier: 'properties',
            component: ImageEditPropertiesFormComponent,
          },
        ];
    }
  }

  getCardTags(): string[] {
    const tags: string[] = [];
    if (this.object.protected) {
      tags.push($localize`protected`);
    }
    return tags;
  }

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