const
db = require('../models'),
Sequelize = require('sequelize');

module.exports = {
	
	get_all: (req, res, next) => {
		let where = {};
		if (req.query.intitule) {
			where.intitule = {
				[Sequelize.Op.like]: '%'+req.query.intitule+'%'
			};
		}
		return db.Tache.findAll({
			order: [ 'intitule' ],
			where
		})
		.then((taches) => res.json(taches))
		.catch((err) => next(err));
	},
	
	load_by_id: (req, res, next) => {
		return db.Tache.findByPk(req.params.tache_id)
		.then((tache) => {
			if (!tache) {
				throw { status: 404, message: 'Requested Tache not found' };
			}
			req.tache = tache;
			return next();
		})
		.catch((err) => next(err));
	},
	
	get_by_id: (req, res, next) => {
		return db.Tache.findByPk(req.params.tache_id)
		.then((tache) => {
			if (!tache) {
				throw { status: 404, message: 'Requested Tache not found' };
			}
			return res.json(tache);
		})
		.catch((err) => next(err));
	},
	
	create: (req, res, next) => {
		const data = {
			intitule: req.body.intitule || '',
			valeur: req.body.valeur || ''
		};
		return db.Tache.create(data)
		.then((tache) => res.json(tache))
		.catch((err) => next(err));
	},
	
	delete_by_id: (req, res, next) => {
		return db.Tache.findByPk(req.params.tache_id)
		.then((tache) => {
			if (!tache) {
				throw { status: 404, message: 'Requested Tache not found' };
			}
			return tache.destroy();
		})
		.then(() => res.status(200).end())
		.catch((err) => next(err));
	}

};
