var Unit = require('../../models/unit'),
    Chapter = require('../../models/chapter'),
    ObjectId = require('mongodb').ObjectId;

function list(req, res, next) {
    Unit.find({}).sort('orderNum').exec(function(err, units) {
        if (err) {console.log(err);}
        res.status(200).send(units);
    });
}

function add(req, res, next) {
    var unit = Unit.create({
        'title': req.body.title,
        'orderNum': req.body.orderNum,
        'content': req.body.content,
        'chapterId': req.body.chapterId
    }, function(err, unit) {
        if (err) {console.log(err);}

        // Increment the orderNum of all the units that have a higher or equal orderNum.
        Unit.find({orderNum: {$gte: unit.orderNum}}).stream().on('data', function(unit) {
            unit.orderNum = unit.orderNum + 1;
            unit.save();
        });
        res.status(201).send(unit);
    });
}

function single(req, res, next) {
    Unit.findById(
        req.params.id,
        function(err, unit) {
            if (err) {console.log(err); }
            if (unit) {
                res.status(200).send(unit);
            } else {
                res.status(404).send('Unit not found');
            }
        }
    );
}

function update(req, res, next) {
    Unit.update(
        {_id: new ObjectId(req.params.id)},
        {
            'title': req.body.title,
            'orderNum': req.body.orderNum,
            'content': req.body.content,
            'chapterId': req.body.chapterId
        },
        function(err, unit) {
            if (err){console.log(err);}
            res.status(200).send(unit);
        }
    );
}

function remove(req, res, next) {
    Unit.findOneAndRemove(
        {_id: new ObjectId(req.params.id)},
        function(err) {
            if (err) {console.log(err);}
            res.status(200).send('Unit removed');
        }
    );
}

module.exports = {
    'list': list,
    'add': add,
    'single': single,
    'update': update,
    'remove': remove
};
