import { ObjectUIServiceBase } from '@objects-view/object-ui-service-base';
import { IProjectModel } from '@fleio-api/openstack/project/model/project.model';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { ProjectsApiService } from '@fleio-api/openstack/project/projects-api.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 { ProjectEditFormComponent } from './tabs/project-edit-form/project-edit-form.component';
import {
  ProjectComputeQuotasEditFormComponent
} from './tabs/project-compute-quotas-edit-form/project-compute-quotas-edit-form.component';
import {
  ProjectNetworkQuotasEditFormComponent
} from './tabs/project-network-quotas-edit-form/project-network-quotas-edit-form.component';
import {
  ProjectVolumeQuotasEditFormComponent
} from './tabs/project-volume-quotas-edit-form/project-volume-quotas-edit-form.component';
import { ProjectSelectRegionComponent } from './components/project-select-region/project-select-region.component';
import { of } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import {
  ProjectDatabaseQuotasEditFormComponent
} from './tabs/project-trove-quotas-edit-form/project-database-quotas-edit-form.component';
import { ProjectDetailsOverviewComponent } from './tabs/project-details-overview/project-details-overview.component';
import { catchError, map } from 'rxjs/operators';
import {
  ProjectClusterQuotasEditFormComponent
} from './tabs/project-cluster-quotas-edit-form/project-cluster-quotas-edit-form.component';
import { EntityAuditLogComponent } from '../../common-components/entity-audit-log/entity-audit-log.component';
import { ProjectRoleAssignmentsComponent } from './tabs/project-role-assignments/project-role-assignments.component';

export class ProjectUiService extends ObjectUIServiceBase<IProjectModel> {
  private readonly datePipe: DateFormatterPipe;

  constructor(
    projectModel: IProjectModel, permissions: IPermissionsModel, state: string,
    private readonly router: Router,
    private readonly config: ConfigService,
    private readonly projectsApiService: ProjectsApiService,
  ) {
    super(projectModel, permissions, state);
    this.datePipe = new DateFormatterPipe(this.config);
  }

  getIcon(): IIcon {
    return null;
  }

  getStatus(): IObjectStatus {
    if (this.object.disabled || this.object.deleted) {
      return {type: StatusType.Defined, value: StatusValue.Disabled};
    } else {
      return {type: StatusType.Defined, value: StatusValue.Enabled};
    }
  }

  getTitle(): ITitle {
    switch (this.state) {
      case 'edit':
        return {
          text: $localize`Edit project ${this.object.name}`,
          subText: this.object.project_id,
        };

      case 'edit-quotas':
        return {
          text: $localize`Edit project ${this.object.name} quotas`,
        };

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

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

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

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

    actions.push(new RouterLinkAction({
        icon: {name: 'tune'},
        name: $localize`Edit quotas`,
        tooltip: $localize`Edit project quotas`,
        routerUrl: this.config.getPanelUrl(`openstack/projects/${this.object.id}/edit-quotas`),
        router: this.router,
        noPermissions: !(
          this.permissions['projects.set_compute_quotas'] || this.permissions['projects.set_network_quotas'] ||
          this.permissions['projects.set_volume_quotas'] || this.permissions['projects.set_database_quotas']
        ),
      }
    ));

    actions.push(new CallbackAction({
      icon: {name: 'delete'},
      name: $localize`Delete`,
      tooltip: $localize`Delete project`,
      redirectAfterExecute: true,
      redirectUrl: this.config.getPanelUrl(`openstack/projects`),
      noPermissions: !this.permissions['projects.delete_project'],
      displayMessages: true,
      confirmOptions: {
        confirm: true,
        title: $localize`Delete project ${this.object.name}(${this.object.id})`,
        message: $localize`Are you sure you want to delete project ${this.object.name}(${this.object.id})?`,
        yesButtonName: $localize`Delete project`,
        noButtonName: $localize`Cancel`,
        flags: [{
          id: 'delete_all_resources',
          message: $localize`Delete all resources`,
          warningOnSelect: $localize`Warning: this will permanently delete data.`,
          selected: false,
        }]
      },
      callback: (action, result) => {
        if (result?.button === 'yes') {
          const deleteAllResources = !!result.flags?.delete_all_resources;
          return this.projectsApiService.deleteProject(
            this.object.id, deleteAllResources,
          ).pipe(map(response => {
            return {
              success: true,
              message: response.detail,
            } as IActionResult;
          }), catchError((error, caught) => {
            return of({success: false, message: error.error.detail} as IActionResult)
          }));
        } else {
          return of({success: false} as IActionResult);
        }
      },
    }));

    return actions;
  }

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

    switch (this.state) {
      case 'create':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/projects`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Create`}));
        break;
      case 'edit':
      case 'edit-quotas':
        actions.push(new RouterLinkAction({
            name: $localize`Cancel`,
            routerUrl: this.config.getPrevUrl(`openstack/projects`),
            router: this.router,
          }
        ));
        actions.push(new CallbackAction({name: $localize`Save`}));
        break;
      case 'details':
        actions.push(new CallbackAction({name: $localize`Update role assignments`}));
        break;
      default:
        break;
    }

    return actions;
  }

  getDetailsLink(): string {
    return this.config.getPanelUrl(`openstack/projects/${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`Updated at`,
        value: this.datePipe.transform(this.object.updated_at),
        title: this.datePipe.getTitleAttributeValue(this.object.updated_at)
      },
    ] as IDataField[];

    if (this.object.service) {
      fields.push({
        value: $localize`Service details`,
        url: this.config.getPanelUrl(`billing/services/${this.object.service}`),
      });
    }

    return fields;
  }

  getTabs(): IDetailsTab[] {
    switch (this.state) {
      case 'create':
        return [
          {
            tabName: $localize`Create`,
            tabIdentifier: 'create',
            component: ProjectEditFormComponent,
          },
        ];
      case 'details':
        return [
          {
            tabName: $localize`Overview`,
            tabIdentifier: 'overview',
            component: ProjectDetailsOverviewComponent,
            hideActions: true,
          },
          {
            tabName: $localize`Role assignments`,
            tabIdentifier: 'role-assignments',
            component: ProjectRoleAssignmentsComponent,
          },
          {
            tabName: $localize`Audit log`,
            tabIdentifier: 'audit-log',
            component: EntityAuditLogComponent,
            featureName: 'utils.activitylog',
            data: {
              entity_type: 'project',
              entity_additional_identifier: 'project_id',
            },
            hideActions: true,
          }
        ];
      case 'edit':
        return [
          {
            tabName: $localize`Edit`,
            tabIdentifier: 'edit',
            component: ProjectEditFormComponent,
          },
        ];
      case 'edit-quotas':
        return [
          {
            tabName: $localize`Compute`,
            tabIdentifier: 'compute',
            component: ProjectComputeQuotasEditFormComponent,
          },
          {
            tabName: $localize`Volume`,
            tabIdentifier: 'volume',
            component: ProjectVolumeQuotasEditFormComponent,
          },
          {
            tabName: $localize`Network`,
            tabIdentifier: 'network',
            component: ProjectNetworkQuotasEditFormComponent,
          },
          {
            tabName: $localize`Trove`,
            tabIdentifier: 'trove',
            component: ProjectDatabaseQuotasEditFormComponent,
          },
          {
            tabName: $localize`Cluster`,
            tabIdentifier: 'cluster',
            component: ProjectClusterQuotasEditFormComponent,
          },
        ];
    }
  }

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

  getHeaderComponent(): any {
    switch (this.state) {
      case 'edit-quotas':
        return {
          position: 'header-right',
          component: ProjectSelectRegionComponent,
        };
      default:
        return null;
    }
  }
}
