Source: classes/books/Term.js

/** @module classes */

const BaseFactory = require('../Base.js');
const TermController = require('../../controllers/TermController.js');
const BookController = require('../../controllers/BookController.js');
const { Book } = require('./Book.js');

/** Class representing a term. */
class Term {
    constructor(id, term) {
        this.id = id;
        this.term = term;
    }

    /** Get the books of the term. */
    async getBooks(forceRefresh = false) {
        if (this.books && !forceRefresh) {
            return this.books;
        }

        this.books = await new BookController().byTerm(this);

        return this.books;
    }

    /** Refreshes data from the database that has been pulled at least once before in this instance. */
    async refresh() {
        if (this.books) {
            await this.getBooks(true);
        }
    }

    /**
     * Link this term to a book.
     * 
     * @param {Book} book
     * @returns {Promise<void>}
     */
    async linkToBook(book) {
        await new TermController().linkTermBook(this.id, book.id);
    }
}

/** Class representing a term factory. */
class TermFactory extends BaseFactory {
    /** Set the id of the term. */
    setId(id) {
        this.id = id;
        
        return this;
    }

    /** Set the term of the term. */
    setTerm(term) {
        this.term = term;
        
        return this;
    }

    /** Load a term from a database object. */
    load(dbObject) {
        this.setId(dbObject.id);
        this.setTerm(dbObject.term);
        
        return this;
    }

    /** Create the term. */
    async create() {
        if (!this.id) {
            return null;
        } else if (!this.term) {
            this.load(await new TermController().byId(this.id));
        }
        
        return new Term(this.id, this.term);
    }
}

module.exports = { Term, TermFactory };