package {
	import adobe.utils.CustomActions;
	import com.netgrind.core.Utils;
	import flash.utils.Dictionary;
	
	/**
	 * ...
	 * @author netgrind
	 */
	public class MissionLoader {
		
		[Embed(source = "../lib/missions.xml", mimeType="application/octet-stream")]public var storyMissions:Class;
		[Embed(source = "../lib/dialog.txt", mimeType="application/octet-stream")]public var dialogText:Class;
		
		public var story:Dictionary;
		public var dialog:Array;
		
		public function MissionLoader() {
			super();
			loadStoryMissions();
		}
		
		public function loadStoryMissions():void {
			dialog = String(new dialogText()).split("\n");
			story = new Dictionary();
			var xml:XML = new XML(new storyMissions);
			var xmlList:XMLList = xml.mission;
			for (var i:int = 0; i < xmlList.length(); i++) {
				story[xmlList[i].attribute("name").toString()] = xmlList[i];
			}
		}
		public function createMission(name:String, callback:Function = null):Mission {
			if (story[name] == null) return null;
			var dia:XMLList;
			var callDialog:Vector.<TextChunk>;
			if ( story[name].call != null) {
				callDialog = new Vector.<TextChunk>();
				dia = story[name].call.dialog;
				for (var l:int = 0; l < dia.length(); l++) {
					callDialog.push( new TextChunk(dialog[dia[l].text-1], Utils.stringToBoolean(dia[l].momTalking), dia[l].characterState, dia[l].momState));
				}
			}			
			var way:XMLList = story[name].waypoint;
			var missionWaypoints:Vector.<MissionWaypoint> = new Vector.<MissionWaypoint>();
			for (var i:int = 0; i < way.length(); i++) {
				dia = way[i].dialog;
				var text:Vector.<TextChunk> = new Vector.<TextChunk>();
				for (var j:int = 0; j < dia.length(); j++) {
					text.push( new TextChunk(dialog[dia[j].text-1], Utils.stringToBoolean(dia[j].momTalking), dia[j].characterState, dia[j].momState));
				}
				missionWaypoints.push(new MissionWaypoint(
					Waypoint.getFromName(way[i].attribute("name").toString()),
					text,
					Utils.stringToBoolean(way[i].requireStop),
					way[i].spawnMission,
					Utils.stringToBoolean(way[i].enterCar),
					Utils.stringToBoolean(way[i].exitCar)
				));
			}
			var m:Mission = new Mission(missionWaypoints, story[name].character, callDialog);
			m.callback = callback;
			if (name.indexOf("RACE") != -1) m.isRace = true;
			var medal:XMLList = story[name].medal;
			for (var k:int = 0; k < medal.length(); k++) {
			trace(medal[k]);
			trace("***");
				m.goalTimes.push(medal[k].time as Number);
				m.goalPoints.push(medal[k].score as Number);
			}			
			return m;
		}
	}
}