/** @module classes */
const { EditionFactory } = require('./Edition.js');
const BaseFactory = require('../Base.js');
const SpineImageController = require('../../controllers/SpineImageController.js');
const fs = require('fs');
/** Class representing a spine image. */
class SpineImage {
constructor(id, editionId, filepath, edition = null) {
this.id = id;
this.editionId = editionId;
this.filepath = filepath;
this.edition = edition;
}
/** Get the edition of the spine image. */
async getEdition(forceRefresh = false) {
if (this.edition && !forceRefresh) {
return this.edition;
}
const editionFactory = new EditionFactory();
editionFactory.setId(this.editionId);
this.edition = await editionFactory.create();
return this.edition;
}
/** Set a meta value for the spine image. */
async setMeta(name, value) {
await new SpineImageController().setMeta(this.id, name, value);
}
/** Get a meta value for the spine image. */
async getMeta(name) {
return await new SpineImageController().getMeta(this.id, name);
}
/** Refreshes data from the database that has been pulled at least once before in this instance. */
async refresh() {
if (this.edition) {
await this.getEdition(true);
}
}
/** Delete the spine image from the database and storage. */
async delete() {
await new SpineImageController().delete(this.id);
fs.unlinkSync(process.env.STORAGE_PATH + '/spine-images/' + this.filepath);
}
}
/** Class representing a spine image factory. */
class SpineImageFactory extends BaseFactory {
/** Set the id of the spine image. */
setId(id) {
this.id = id;
return this;
}
/** Set the edition id of the spine image. */
setEditionId(editionId) {
this.editionId = editionId;
return this;
}
/** Set the filepath of the spine image. */
setFilepath(filepath) {
this.filepath = filepath;
return this;
}
/** Set the edition of the spine image. */
setEdition(edition) {
this.edition = edition;
return this;
}
/** Loads data from a database object */
load(dbObject) {
this.setId(dbObject.id);
this.setEditionId(dbObject.edition_id);
this.setFilepath(dbObject.filepath);
return this;
}
/** Creates a spine image object */
async create() {
if (!this.id) {
throw new Error('Missing required fields for Spine Image');
} else if (!this.editionId && !this.filepath) {
const spineImageDb = await new SpineImageController().byId(this.id);
if (!spineImageDb) {
return null;
}
this.load(spineImageDb);
}
return new SpineImage(this.id, this.editionId, this.filepath, this.edition);
}
}
module.exports = { SpineImage, SpineImageFactory };