'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors'),
	Picture = mongoose.model('Picture'),
	uuid = require('uuid'),
	util = require('util'),
	multiparty = require('multiparty'),
  fs = require('fs'),
	_ = require('lodash');

/**
 * Upload a Picture
 */
exports.upload = function(req, res) {
	var form = new multiparty.Form();
	form.on('error', function(err) {
  	console.log('Error parsing form: ' + err.stack);
	});
	form.parse(req ,function(err, fields, files) {
		var file = files.file[0];
		var extension = file.path.substring(file.path.lastIndexOf('.'));
		var newpath = './public/modules/pictures/img/'+uuid.v4()+extension;
		var source = fs.createReadStream(file.path);
		var dest = fs.createWriteStream(newpath);
		var publicpath = newpath.substring(9);
		var response = {};
		response.public_url = publicpath;
		response.private_url = newpath;
		source.pipe(dest);
		source.on('end', function() {
			res.jsonp(response);
		});
		source.on('error', function(err) {
			throw err;
		});
	});
	
	form.on('part', function(part) {
  // You *must* act on the part by reading it
  // NOTE: if you want to ignore it, just call "part.resume()"

  	if (part.filename === null) {
    	// filename is "null" when this is a field and not a file
    	console.log('got field named ' + part.name);
    	// ignore field's content
    	part.resume();
  	}
	});

	form.on('close', function() {
  	console.log('Upload completed!');
	});

	
};

/**
 * Create a Picture
 */
exports.create = function(req, res) {
	util.inspect(req);
	var picture = new Picture(req.body);
	picture.user = req.user;
	picture.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(picture);
		}
	});
};

/**
 * Show the current Picture
 */
exports.read = function(req, res) {
	res.jsonp(req.picture);
};

/**
 * Update a Picture
 */
exports.update = function(req, res) {
	var picture = req.picture ;

	picture = _.extend(picture , req.body);

	picture.save(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(picture);
		}
	});
};

/**
 * Delete an Picture
 */
exports.delete = function(req, res) {
	var picture = req.picture ;

	picture.remove(function(err) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(picture);
		}
	});
};

/**
 * List of Pictures
 */
exports.list = function(req, res) { Picture.find().sort('-created').populate('user', 'displayName').exec(function(err, pictures) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(pictures);
		}
	});
};

/**
 * Picture middleware
 */
exports.pictureByID = function(req, res, next, id) { Picture.findById(id).populate('user', 'displayName').exec(function(err, picture) {
		if (err) return next(err);
		if (! picture) return next(new Error('Failed to load Picture ' + id));
		req.picture = picture ;
		next();
	});
};

/**
 * Picture authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.picture.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};
