const db = require('../models');

module.exports = {
	
	get_all: (req, res, next) => {
		let where = {};
		if (req.query.date) {
			where.date = req.query.date;
		}
		return req.participant.getActions({
			order: [ 'date' ],
			where
		})
		.then((actions) => res.json(actions))
		.catch((err) => next(err));
    },
    get_all_all: (req, res, next) => {
		let where = {};
		if (req.query.date) {
			where.date = {
				[Sequelize.Op.like]: '%'+req.query.date+'%'
			};
		}
		return db.Action.findAll({
			order: [ 'date' ],
			where
		})
		.then((actions) => res.json(actions))
		.catch((err) => next(err));
	},
	
	get_by_id: (req, res, next) => {
		return req.participant.getActions({
			where: {
				id: req.params.date_id
			}
		})
		.then((actions) => {
			if (actions.length === 0) {
				throw { status: 404, message: 'Requested action not found' };
			}
			return res.json(actions[0]);
		})
		.catch((err) => next(err));
	},

	create: (req, res, next) => {
		const data = {
			date: req.body.date || new Date()
		};
		return req.participant.createAction({...data, TacheId: req.tache.id})
		.then((action) => res.json(action))
		.catch((err) => next(err));
	},

	delete_by_id: (req, res, next) => {
		return req.participant.getActions({
			where: {
				id: req.params.date_id
			}
		})
		.then((actions) => {
			if (actions.length === 0) {
				throw { status: 404, message: 'Requested action not found' };
			}
			return actions[0].destroy();
		})
		.then(() => res.status(200).end())
		.catch((err) => next(err));
	}

};
