"use strict";

var os = require('os'),
	gm = require('gm').subClass({ imageMagick: true }),
	fs = require('fs'),
	plugin = {};

if (os.platform() === 'linux') {
	require('child_process').exec('/usr/bin/which convert', function(err, stdout, stderr) {
		if(err || !stdout) {
			winston.warn('Couldn\'t find convert. Did you install imagemagick?');
		}
	});
}

plugin.resize = function(data, callback) {
	function done(err, stdout, stderr) {
		callback(err);
	}

	if(data.extension === '.gif') {
		gm().in(data.path)
			.in('-coalesce')
			.in('-resize')
			.in(data.width+'x'+data.height+'^')
			.write(data.target || data.path, done);
	} else {
		gm(data.path)
			.in('-resize')
			.in(data.width+'x'+data.height+'^')
			.gravity('Center')
			.crop(data.width, data.height)
			.write(data.target || data.path, done);
	}
};

plugin.size = function(data, callback) {
	gm(data.path).size(function (err, size) {
		if (err) {
			return callback(err);
		}
		var image = {
			path: data.path,
			width: size.width,
			height: size.height
		};
		callback(null, image);
	});
};

plugin.fileTypeAllowed = function(path, callback) {
	callback();
};

plugin.normalise = function(data, callback) {
	gm(data.path).toBuffer('png', function(err, buffer) {
		if (err) {
			return callback(err);
		}
		fs.writeFile(data.path + '.png', buffer, 'binary', callback);
	});
};

module.exports = plugin;

@@ -531,36 +531,22 @@
 e')%0A%09%09%09.
-in('-
 resize
-')%0A%09%09%09.in
 (data.wi
@@ -540,37 +540,42 @@
 esize(data.width
-+'x'+
+ %7C%7C null, 
 data.height+'%5E')
@@ -565,28 +565,32 @@
  data.height
-+'%5E'
+ %7C%7C null
 )%0A%09%09%09.write(
@@ -656,28 +656,14 @@
 %09%09%09.
-in('-
 resize
-')%0A%09%09%09.in
 (dat
@@ -673,71 +673,16 @@
 idth
-+'x'+data.height+'%5E')%0A%09%09%09.gravity('Center')%0A%09%09%09.crop(data.width
+ %7C%7C null
 , da
@@ -690,16 +690,24 @@
 a.height
+ %7C%7C null
 )%0A%09%09%09.wr

fix resize if data.width or data.height is undefined