(function () {
    'use strict';


	// --------------------------------------------------------------------------------
	// Private attributes & includes
	// --------------------------------------------------------------------------------
		
		var _ = require('lodash');
		var fs = require('fs');
		var config = require('../../config/environment');
		var formidable = require('formidable');
		var gm = require('gm');
		var imgDirBase = config.env === 'development' ? './client' : './public';
		var imgDirSub = '/assets/images/';

	// --------------------------------------------------------------------------------
	// Private functions
	// --------------------------------------------------------------------------------

		function errorhandler(err,res) {
			console.log('Error...: ',err);
			return res.send(500).json(err);
		}



	// --------------------------------------------------------------------------------
	// Public methods
	// --------------------------------------------------------------------------------

		// Load single image file to server
		exports.load = function(req,res,next) {
			var form = new formidable.IncomingForm();
			var fileName;
			var fileDir;

			form.uploadDir = imgDirBase + imgDirSub;
			form.keepExtensions = true;
		    form.on('field', function(name, value) {
		    	value = JSON.parse(value);
		    	if( !fs.existsSync( form.uploadDir + value.user )){ fs.mkdirSync( form.uploadDir + value.user )}
		    	fileDir = form.uploadDir+value.user + '/';
		    	fileName = Date.parse(new Date()) + '-' + value.type;
			});
			form.on ('fileBegin', function(name, file){
		        file.ext = '.' + file.path.substr(file.path.lastIndexOf('.')+1,file.path.length);
		        file.path = fileDir + fileName + file.ext;
		    })


			form.parse(req, function (err,fields,files) {
				if(err) { return errorhandler(err,res); }
				if(!files.file) { return res.send(404); }
				req.file = files.file;
				next();
			})
		}


		exports.crop = function(req,res,next){
			var file = req.file;
			var newPath;

			if(file && file.path){
				newPath = file.path.replace(file.ext,'') + '-cropped' + file.ext;

				gm(file.path)
					.quality(100)
					.gravity('Center')
					.crop(320,150)
					.write(newPath,function (err){

						if(err) { return errorhandler(err,res); }
						file.path = newPath.replace(imgDirBase + '/','');
						res.json(200,file);
						
					});
			}
			else { errorhandler('Error: No such file',res); }
		}


		exports.remove = function(req,res){

			if(req.query.fileName){
				var pathsToDelete = [
					imgDirBase + imgDirSub + req.query.userId + '/' + req.query.fileName,
					imgDirBase + imgDirSub + req.query.userId + '/' + req.query.fileName.replace('-cropped',''),
				]

				_.forEach(pathsToDelete,function(item){
					if(item){
						fs.unlink(item, function(err){
							if(err) { return errorhandler(err,res); }
						})
					}			
				})

				res.send(200);
			}
		}

}());