'use strict';
var os = require('os');
var path = require('path');
var execFile = require('child_process').execFile;
var escapeStringApplescript = require('escape-string-applescript');
var runApplescript = require('run-applescript');
var olderThanMountainLion = Number(os.release().split('.')[0]) < 12;

function legacy(paths, cb) {
	var script =
		'set deleteList to {}\n' +
		'repeat with currentPath in ' + '{' + paths.map(function (el) {
			return '"' + escapeStringApplescript(el) + '"';
		}).join(',') + '}' + '\n' +
		'set end of deleteList to POSIX file currentPath\n' +
		'end repeat\n' +
		'tell app "Finder" to delete deleteList';

	runApplescript(script, function (err) {
		if (err && /10010/.test(err.message)) {
			cb(new Error('Item doesn\'t exist'));
			return;
		}

		cb(err);
	});
}

module.exports = function (paths, cb) {
	cb = cb || function () {};

	if (process.platform !== 'darwin') {
		throw new Error('OS X only');
	}

	if (!Array.isArray(paths)) {
		throw new Error('Please supply an array of filepaths');
	}

	if (paths.length === 0) {
		setImmediate(cb);
		return;
	}

	paths = paths.map(function (el) {
		return path.resolve(String(el));
	});

	if (olderThanMountainLion) {
		legacy(paths, cb);
		return;
	}

	execFile('./trash', paths, {cwd: __dirname}, function (err) {
		cb(err);
	});
};
