"use strict";
this.name        = "dictators.js";
this.author      = "Ramirez";
this.copyright   = "June 2010";
this.description = "World script for populating dictatorship systems";
this.version     = "1.2";

this._shipSpawnOverride = false;
this._settings = {
	policeShipReplace: true,
};

this._config = {
	Name: this.name,
	Alias: "Dictators",
	Display: "General settings",
	Alive: "_config",
	Bool: {
		B0: { Name: "_settings.policeShipReplace", Def: true, Desc: "Police are replaced" },
		Info: "0: Police ships will be replaced by Dictators equivalents."
	},
};

//-------------------------------------------------------------------------------------------------------------
this.startUp = function() {
	if (missionVariables.Dictators_Settings) {
		this._settings = JSON.parse(missionVariables.Dictators_Settings);
	}
}

//-------------------------------------------------------------------------------------------------------------
this.startUpComplete = function() {
	// register our settings, if Lib_Config is present
	if (worldScripts.Lib_Config) {
		var lib = worldScripts.Lib_Config;
		lib._registerSet(this._config);
	}
}

//-------------------------------------------------------------------------------------------------------------
this.playerWillSaveGame = function() {
	missionVariables.Dictators_Settings = JSON.stringify(this._settings);
}

//-------------------------------------------------------------------------------------------------------------
this.shipWillDockWithStation = function(station) {
	if (system.government == 3 && station.isMainStation) {
		if (Math.random() < 0.1) {
			player.addMessageToArrivalReport(expandDescription("[ambience_arrival]"));
		}
	}
}

//-------------------------------------------------------------------------------------------------------------
this.systemWillPopulate = function() {
	if (system.government === 3) {
		var sv = worldScripts.station_validator;

		// astrofactory spawning
		if (system.economy < 3) {
			if (system.countShipsWithRole("astrofactory") == 0 && (!sv || (sv.$deaths("dfl_astrofactory").length === 0 && sv.$deaths("dfl_astrofactory2").length === 0))) {
				var posAF = Vector3D((system.scrambledPseudoRandomNumber(1245) * 0.30 - 0.15), (system.scrambledPseudoRandomNumber(3827) * 0.30 - 0.15), 0.3).fromCoordinateSystem("wpu");
				system.setPopulator("dictators_astrofactory", {
					location: "COORDINATES",
					coordinates: posAF,
					deterministic:true,
					callback: function(pos) {
						var rck = system.addShips("asteroid", 30, pos, 40E3);
						var key = "dfl_astrofactory";
						if (system.techLevel >= 10) key = "dfl_astrofactory2";
						var af = system.addShips("[" + key + "]", 1, pos, 0);
						if (!af || af.length === 0) log("dictators.populator", "OOPS! No astrofactory spawned");
					}}
				);

				var posIT1 = Vector3D(0, 0, 0.8).fromCoordinateSystem("wpu");
				system.setPopulator("dictators_imptanker1", {
					location: "COORDINATES",
					coordinates: posIT1,
					callback: function(pos) {
						var tnk = system.addShips("imptanker", 1, pos);
						if (!tnk || tnk.length === 0) log("dictators.populator", "OOPS! No imptanker spawned (1)");
					}}
				);

				var posIT2 = Vector3D(0, 0, 0.4).fromCoordinateSystem("wpu");
				system.setPopulator("dictators_imptanker2", {
					location: "COORDINATES",
					coordinates: posIT2,
					callback: function(pos) {
						var tnk = system.addShips("imptanker", 1, pos);
						if (!tnk || tnk.length === 0) log("dictators.populator", "OOPS! No imptanker spawned (2)");
					}}
				);

				var posIF1 = Vector3D(0, 0, 0.3).fromCoordinateSystem("wpu");
				system.setPopulator("dictators_impfreighter1", {
					location: "COORDINATES",
					coordinates: posIF1,
					callback: function(pos) {
						var frt = system.addShips("impfreighter", 1, pos);
						if (!frt || frt.length === 0) log("dictators.populator", "OOPS! No impfreighter spawned (1)");
					}}
				);

				var posIF2 = Vector3D(0, 0, 0.7).fromCoordinateSystem("wpu");
				system.setPopulator("dictators_impfreighter2", {
					location: "COORDINATES",
					coordinates: posIF2,
					callback: function(pos) {
						var frt = system.addShips("impfreighter", 1, pos);
						if (!frt || frt.length === 0) log("dictators.populator", "OOPS! No impfreighter spawned (2)");
					}}
				);
			}
		}
		
		// astrofarm spawning
		if (system.economy > 4) {
			if (system.countShipsWithRole("astrofarm") == 0 && (!sv || (sv.$deaths("dfl_astrofarm").length === 0 && sv.$deaths("dfl_astrofarm2").length === 0))) {
				var posAFM = Vector3D((system.scrambledPseudoRandomNumber(2271) * 0.30 - 0.15), (system.scrambledPseudoRandomNumber(772) * 0.30 - 0.15), 0.3).fromCoordinateSystem("spu");
				system.setPopulator("dictators_astrofarm", {
					location: "COORDINATES",
					coordinates: posAFM,
					deterministic:true,
					priority: 200,
					callback: function(pos) {
						var key = "dfl_astrofarm";
						if (system.techLevel >= 6) key = "dfl_astrofarm2";
						var af = system.addShips("[" + key + "]", 1, pos);
						if (!af || af.length === 0) 
							log("dictators.populator", "OOPS! No astrofarm spawned");
						else 
							worldScripts["dictators.js"].turnStationToEntity(af[0], system.sun, -1.5, 0, 1); // get solar panel to face sun
					}}
				);

				var posIM1 = Vector3D.interpolate(posAFM, system.mainStation.position, 0.8);
				system.setPopulator("dictators_revlogistics1", {
					location: "COORDINATES",
					coordinates: posIM1,
					priority: 400,
					callback: function(pos) {
						if (system.countShipsWithRole("astrofarm") == 0) return;
						var mnc = system.addShips("revlogistics", 1, pos);
						if (!mnc || mnc.length === 0) log("dictators.populator", "OOPS! No revlogistics spawned (1)");
					}}
				);

				var posIM2 = Vector3D.interpolate(posAFM, system.mainStation.position, 0.4);
				system.setPopulator("dictators_revlogistics2", {
					location: "COORDINATES",
					coordinates: posIM2,
					priority: 400,
					callback: function(pos) {
						if (system.countShipsWithRole("astrofarm") == 0) return;
						var tnk = system.addShips("revlogistics", 1, pos);
						if (!tnk || tnk.length === 0) log("dictators.populator", "OOPS! No revlogistics spawned (2)");
					}}
				);
			}
		}

		// prisonship spawning
		if(system.economy >= 6) {
			if(system.countShipsWithRole("prisonship") == 0) {
				var posPS = Vector3D(0, 0, 0.8).fromCoordinateSystem("wpu");
				system.setPopulator("dictators_prisonship", {
					location: "COORDINATES",
					coordinates: posPS,
					callback: function(pos) {
						var ps = system.addShips("prisonship", 1, pos);
						if (!ps || ps.length === 0) log("dictators.populator", "OOPS! No prisonship spawned");
					}}
				);
			}
		}

		if (Math.random() > 0.09) {
			// spawn some ambience near the witchpoint
			system.setPopulator("dictators_ambience", {
				callback: function(pos) {
					var ambienceAttacker = "censor_ambience";
					if (system.economy >= 4) ambienceAttacker = "enforcer_ambience";
					//half the time, spawn ambience ships close to the witchpoint and move them a bit closer to the planet. a bit is a 0.75 * scanner range. it's a bit boring to all the time have them sitting next to the witchpoint. a bit too staged to my liking.
					if (Math.random() < 0.5) {
						var attk = system.addShips("[" + ambienceAttacker + "]", 1);
						if (attk.length > 0) {
							var attacker = attk[0];
							attacker.position = attacker.position.add([0, 0, 19200]);
							var target = system.addShips("trader", 1, attacker.position)[0];
						}
					}
					else {
						var attk = system.addShips("[" + ambienceAttacker + "]", 1);
						if (attk.length > 0) {
							var attacker = attk[0];
							var target = system.addShips("trader", 1, attacker.position)[0];
						}
					}
					if (target) {
						target.$dictatorsAmbience = true;
						target.fuel = 0;//no escape
						target.script.shipDied = worldScripts["dictators.js"].$ambienceTargetShipDied;
					}
				}.bind(this),
				location: "LANE_WP"
			});
		}
	}
}

//-------------------------------------------------------------------------------------------------------------
this.turnStationToEntity = function (station, entity, x, y, z) {
	var targetVector = entity.position.subtract(station.position).direction();
	station.orientation = targetVector.rotationTo([(!x ? 0 : x), (!y ? 0 : y), (!z ? 1 : z)]);
}

//-------------------------------------------------------------------------------------------------------------
this.$ambienceTargetShipDied = function(whom, why) {
	function $findAmbienceAttacker(entity) {
		return entity.isShip && entity.hasRole("dictatorsAmbience");;
	}
	var targets = system.filteredEntities(this, $findAmbienceAttacker, this.ship, 35600);
	if (targets.length > 0) {
		if (targets[0].hasRole("imperial")) {
			targets[0].switchAI("imperialpoliceAI.plist");
		}
		if (targets[0].hasRole("junta")) {
			targets[0].switchAI("juntapoliceAI.plist");
		}
	}
}