/**
 * @file commentsController.js
 * @author Radim Buráň (xburan03@stud.fit.vutbr.cz)
 */

const service = require('../services/commentsServices');
const utility = require('../utility');

const createInclude = (req) => {
    const include = {
        owner: req.query.owners ? Boolean(req.query.owners) : false,
        preset: req.query.presets ? Boolean(req.query.presets) : false
    }
    return include;
}

const post = (req, res) => {
    const data = req.body;
    const userID = Number(data.ownerID);
    const presetID = Number(data.presetID);
    const text = data.text;

    service.createForUser(userID, presetID, text).then((user) => {
        res.status(utility.getResStatus(user))
            .json(user);
    });
}

const getByID = (req, res) => {
    const id = Number(req.params.id);
    const include = createInclude(req);
    service.getByID(id, include).then((user) => {
        res.status(utility.getResStatus(user))
            .json(user);
    });
}

const patch = (req, res) => {
    const changes = req.body;
    if (Object.keys(changes).length === 0) {
        res.status(200).json({ message: "Nothing changed!" });
    }
    service.update(changes).then((user) => {
        res.status(utility.getResStatus(user))
            .json(user);
    });
}

const deleteByID = (req, res) => {
    const id = Number(req.params.id);
    service.deleteByID(id).then((user) => {
        res.status(utility.getResStatus(user))
            .json(user);
    });
}

const getByFilter = (req, res) => {
    const filter = {};
    filter.id = req.query.id;
    filter.owner = req.query.owner;
    filter.preset = req.query.preset;
    const max_items = Number(req.query.max_items);
    const page = Number(req.query.page);
    const include = createInclude(req);
    service.getByFilter(filter, include, max_items || 20, page || 0).then((data) => {
        data.items = data?.items.map(comment => {
            delete comment.owner.password;
            return comment;
        });

        res.status(utility.getResStatus(data))
            .json(data);
    });
}

module.exports = {
    getByID,
    post,
    patch,
    deleteByID,
    getByFilter
}