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

const service = require('../services/devicesServices');
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
    }
    if (include.preset === true) {
        include.preset = {
            select: {
                deviceId: true,
                id: true,
                data: true
            }
        }
    }
    return include;
}

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

    service.createForUser(userID, data).then((dev) => {
        res.status(utility.getResStatus(dev))
            .json(dev);
    });
}

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

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((dev) => {
        res.status(utility.getResStatus(dev))
            .json(dev);
    });
}

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

const getByFilter = (req, res) => {
    const filter = {};
    filter.id = req.query.id;
    filter.name = req.query.name;
    filter.owner = req.query.owner;
    filter.ownerId = req.query.ownerId;
    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((dev) => {
        res.status(utility.getResStatus(dev))
            .json(dev);
    });
}

const getMy = (req, res) => {
    const userID = req?.user?.id;
    if (userID === undefined || userID === null) {
        return res.status(404).json({error: "No user in request"});
    }
    req.query.ownerId = userID;
    getByFilter(req, res);
}

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