var ModSupport = {};

//superb start

ModSupport.availableMods = [];

ModSupport.modsDescriptionsToLoad = 0;

ModSupport._loadModDescription = function (file) {
	Windows.Storage.FileIO.readTextAsync(file).then(function (content) {
		try{
			var packageDescription = JSON.parse(content);
			packageDescription.folder = file.path.replace('\\package.json', '');
			ModSupport.availableMods.push(packageDescription);
			ModSupport.modsDescriptionsToLoad--;
			//ModSupport.loadMods();
		}catch(e){
			Logger.LogModError('Could not parse package.json: {0}'.format(file.path), e, 'Could not parse package.json: {0}'.format(file.path));
		}
	}, function () {
		ModSupport.modsDescriptionsToLoad--;
		//ModSupport.loadMods();
	});
};

ModSupport.loadMods = function () {
	if (ModSupport.modsDescriptionsToLoad == 0) {
		var enabledMods = JSON.parse(DataStore.getValue('enabledMods'));
		for (var i = 0; i < ModSupport.availableMods.length; i++) {
			ModSupport.availableMods[i].active = enabledMods.first(function (f) { return f == ModSupport.availableMods[i].id; }) != undefined;
		}
		var i = 0;
		GDT.on(GDT.eventKeys.mod.loaded, function (e) {
			ModSupport.loadMod(enabledMods, ++i);
		});
		GDT.on(GDT.eventKeys.mod.loadError, function (e) {
			ModSupport.loadMod(enabledMods, ++i);
		});
		ModSupport.loadMod(enabledMods, i);
	}
};

ModSupport.loadMod = function (enabledMods, i) {
	try {
		if (enabledMods.length > i) {
			var mod = ModSupport.availableMods.first(function (f) {
				return f.id == enabledMods[i];
			});
			GDT.loadJs(['{0}/{1}'.format(mod.folder, mod.main)], function (util) {
				return;
			}, function (util) {
				var text= 'Could not load mod';
				Logger.LogModError(text, util, text);
			});
		}
	} catch (e) {
		Logger.LogModError('Could not load mod: {0}'.format(i + 1), e, "Could not load mod nr. {0}".format(i + 1));
	}
};

ModSupport.sortMods = function () {
	var enabledMods = JSON.parse(DataStore.getValue('enabledMods'));
	var modsToRemove = [];
	//enabled mods first
	for (var i = enabledMods.length -1; i >= 0; i--) {
		var currentMod = ModSupport.availableMods.first(function (f) { return f.id == enabledMods[i]; });
		if (currentMod != undefined) {
			ModSupport.availableMods.remove(currentMod);
			ModSupport.availableMods.insertAt(0, currentMod);
			currentMod.active = true;
		} else {
			modsToRemove.push(enabledMods[i]);
		}
	}
	for (var i = 0; i < modsToRemove.length; i++) {
		enabledMods.remove(modsToRemove[i]);
	}
	if (modsToRemove.length > 0) {
		DataStore.setValue('enabledMods', JSON.stringify(enabledMods));
	}
	//order by dependencies
	var modsChecked = [];
	var checkMod = ModSupport.availableMods.first(function(f){return f.id != modsChecked.first(function(x){return x == f.id;});});
	while (checkMod != undefined) {
		if (checkMod.dependencies != undefined) {
			var unresolvedDependency = undefined;
			for (var key in checkMod.dependencies) {
				if (checkMod.dependencies.hasOwnProperty(key)) {
					if (modsChecked.first(function (f) { return f == key; }) == undefined) {
						unresolvedDependency = key;
						if (ModSupport.availableMods.first(function (f) { return f.id == key; }) == undefined) {
							checkMod.unresolvedDependency = true;
						}
					}
				}
			}
			if (unresolvedDependency == undefined) {
				modsChecked.push(checkMod.id);
			}
			if (checkMod.unresolvedDependency) {
				modsChecked.push(checkMod.id);
				ModSupport.availableMods.remove(checkMod);
				ModSupport.availableMods.push(checkMod);
				if (enabledMods.first(function (f) { return f == checkMod.id; }) != undefined) {
					enabledMods.remove(checkMod.id);
					checkMod.active = false;
				}
			} else if(unresolvedDependency != undefined) {
				ModSupport.availableMods.remove(checkMod);
				var index = ModSupport.availableMods.indexOf(ModSupport.availableMods.first(function(f){return f.id == unresolvedDependency;}));
				ModSupport.availableMods.insertAt(index + 1, checkMod);
			}
		} else {
			modsChecked.push(checkMod.id);
		}
		checkMod = ModSupport.availableMods.first(function (f) { return f.id != modsChecked.first(function (x) { return x == f.id; }); });
	};
};

ModSupport.disableMod = function (mod) {
	var enabledMods = JSON.parse(DataStore.getValue('enabledMods'));
	if (enabledMods.first(function (f) { return f == mod.id; }) != undefined) {
		enabledMods.remove(mod.id);
		mod.active = false;
		DataStore.setValue('enabledMods', JSON.stringify(enabledMods));
		for (var i = 0; i <= enabledMods.length; i++) {
			var modToRemove = ModSupport.availableMods.first(function (f) { return f.id == enabledMods[i] && f.dependencies != undefined && f.dependencies.hasOwnProperty(mod.id); });
			if (modToRemove != undefined) {
				ModSupport.disableMod(modToRemove);
			}
		}
	}
};

ModSupport.enableMod = function (mod) {
	if (!mod.unresolvedDependency) {
		var enabledMods = JSON.parse(DataStore.getValue('enabledMods'));
		if (enabledMods.first(function (f) { return f == mod.id; }) == undefined) {
			if (mod.dependencies != undefined) {
				for (var key in mod.dependencies) {
					ModSupport.enableMod(ModSupport.availableMods.first(function (f) { return f.id == key; }));
					enabledMods = JSON.parse(DataStore.getValue('enabledMods'));
				}
			}
			enabledMods.push(mod.id);
			mod.active = true;
			DataStore.setValue('enabledMods', JSON.stringify(enabledMods));
		}
	}
};

(function () {
	var enabledMods = DataStore.getValue('enabledMods');
	if (enabledMods == undefined) {
		DataStore.setValue('enabledMods', JSON.stringify([]));
		enabledMods = [];
	}
	if (!PlatformShim.ISWIN8 && require) {
		var fs = require('fs');

		var folders = fs.readdirSync('mods');
		for (var i = 0; i < folders.length; i++) {
			try {
				var files = fs.readdirSync('mods/' + folders[i]);
				for (var j = 0; j < files.length; j++) {
					if (files[j] == 'package.json') {
						try {
							var packageDescription = require('./mods/' + folders[i] + '/' + files[j]);
							packageDescription.folder = 'mods/' + folders[i];
							ModSupport.availableMods.push(packageDescription);
						} catch (e) {
							Logger.LogModError('Could not parse package.json: {0}'.format('./mods/' + folders[i] + '/' + files[j]), e, 'Could not parse package.json: {0}'.format('./mods/' + folders[i] + '/' + files[j]));
						}
					}
				}
			} catch (e) {
			}
		}
		ModSupport.loadMods();
	} else if (PlatformShim.ISWIN8) {
		var location = Windows.ApplicationModel.Package.current.installedLocation;
		location.path += '\mods';
		var options = new Windows.Storage.Search.QueryOptions(Windows.Storage.Search.CommonFileQuery.orderBySearchRank, ['.json']);
		options.userSearchFilter = 'package';
		var fileQuery = location.createFileQueryWithOptions(options);
		fileQuery.getFilesAsync().done(function (files) {
			ModSupport.modsDescriptionsToLoad = files.length;
			for (var j = 0; j < files.length; j++) {
				try{
					ModSupport._loadModDescription(files[j]);
				} catch (e) {
					Logger.LogModError('Could not parse package.json: {0}'.format(files[j]), e, 'Could not parse package.json: {0}'.format(files[j]));
				}
			}
		});
	}
})();
//superb end