var AbstractFileManager = require("less/environment/abstract-file-manager");
var importer = new AbstractFileManager();
importer.supports = function() { return true; };
importer.supportsSync = function() { return true; };
importer.loadFileSync = function(filename, currentDirectory, options, environment, encoding)
{
	if (currentDirectory.length > 0) {
		filename = currentDirectory + filename
	}
	
	var importContext, text;
	try {
		importContext = importer.activeContext.compilerContextForDocument(filename);
		text = importContext ? importContext.textContext.string : null;
	} catch (error) { return { error: error }; }
	
	if (typeof text === "string") {
		return {
			filename: importContext.sourcePath,
			contents: text
		}
	}
	return { error: { message: "Couldn't find " + (currentDirectory || "") + filename} };
};
importer.loadFile = function(filename, currentDirectory, options, environment, callback)
{
	var data = this.loadFileSync(filename, currentDirectory, options, environment, 'utf-8');
	callback(data.error, data);
};
importer.activeContext = null;

var less = require('less')(null, [importer]);

compiler.compileWithContextAsync = function(context, async)
{
	importer.activeContext = context;
	var fail = function(error) {
		importer.activeContext = null;
		async.fail(error);
	};
	
	try {
		less.parse(context.text, {}, function(error, root, imports, options) {
			
			if (error) { return fail(error); }
			
			var result;
			try {
				var parseTree = new less.ParseTree(root, imports);
				result = parseTree.toCSS(options);
			}
			catch (error) { return fail(error); }
			
			if (result.sourceMap) {
				context.didBuildSourceMap(result.sourceMap);
			}
			
			context.didCompileToText(result.css);
			importer.activeContext = null;
			async.finish();
		});
	}
	catch (error) {
		fail(error);
	}
};
