import {IJsonSchema} from '@jacquesparis/objects-model';
import {Getter, inject, service} from '@loopback/core';
import {Entity, model, property, repository} from '@loopback/repository';
import {DATASTORE_DB} from '../../constants';
import {DbDataSource} from '../../datasources/db.datasource';
import {
  ContentExtension,
  ContentExtensionRelations,
  ContentExtensionRepository,
  ContentExtensionService,
  ContentExtensionWithRelations,
} from '../../integration/content-extension.definition';
import {ObjectNodeRepository} from '../../repositories/object-node.repository';
import {ContentEntityService} from '../../services/content-entity/content-entity.service';
import {CONTENT_FILE_PROVIDER} from './content-file.const';

@model()
export class File extends Entity {
  @property({
    type: 'string',
  })
  base64: string;
  @property({
    type: 'string',
  })
  size: string;
  @property({
    type: 'string',
  })
  name: string;
  @property({
    type: 'string',
  })
  type: string;
}

@model({settings: {strict: false}})
export class ContentFile extends ContentExtension<File> {}

export type ContentFileRelations = ContentExtensionRelations;

export type ContentFileWithRelations = ContentExtensionWithRelations<File>;

export class ContentFileRepository extends ContentExtensionRepository<
  File,
  typeof ContentFile.prototype.id
> {
  constructor(
    @inject(DATASTORE_DB) dataSource: DbDataSource,
    @repository.getter('ObjectNodeRepository')
    protected objectNodeRepositoryGetter: Getter<ObjectNodeRepository>,
  ) {
    super(ContentFile, dataSource, objectNodeRepositoryGetter);
  }
}

export class ContentFileService extends ContentExtensionService<
  File,
  typeof ContentFile.prototype.id
> {
  constructor(
    @service(ContentEntityService)
    protected contentEntityService: ContentEntityService,
    @repository(ContentFileRepository)
    protected contentExtensionRepository: ContentFileRepository,
  ) {
    super(
      CONTENT_FILE_PROVIDER,
      ContentFileService.name,
      contentEntityService,
      contentExtensionRepository,
      'ContentFile',
    );
  }

  public async getContentDefinition(): Promise<IJsonSchema> {
    return {
      properties: {
        contentFile: {
          type: 'object',
          title: 'File',
          'x-schema-form': {
            type: 'file',
          },
          properties: {
            base64: {type: 'string', required: false},
            size: {type: 'string', required: false},
            name: {type: 'string', required: false},
            type: {type: 'string', required: false},
            id: {type: 'string', required: false},
            uri: {type: 'string', required: false},
          },
        },
      },
    };
  }
}
