"use strict";
this.name = "TCAT_missionScript";
this.author = "Thargoid";
this.copyright = "Creative Commons: attribution, non-commercial, sharealike with clauses - see readme.txt";
this.description = "Mission script for TCAT OXP.";
this.version = "2.0";

//----------------------------------------------------------------------------------------
this.startUp = function () {
	// mission has already been rejected or completed, clean up and remove active script parts
	if (missionVariables.TCAT_mission == "CASE_CLOSED") {
		this.cleanUp();
		return;
	}

	this.warningSound = new SoundSource;
	this.warningSound.sound = "TCAT_alert.ogg";
	this.warningSound.loop = false;

	//initialise mission variables
	if (!missionVariables.TCAT_sneakCount) {
		missionVariables.TCAT_sneakCount = 0;
	}

	if (!missionVariables.TCAT_missionBlock) {
		missionVariables.TCAT_missionBlock = false;
	}

	if (!missionVariables.TCAT_navalStatus || (missionVariables.TCAT_navalStatus != "ALIVE" && missionVariables.TCAT_navalStatus != "DEAD")) {
		missionVariables.TCAT_navalStatus = "ALIVE";
	}
}

//----------------------------------------------------------------------------------------
this.cleanUp = function () { // get rid of active script elements if no longer needed.
	delete this.shipLaunchedFromStation;
	delete this.playerEnteredNewGalaxy;
	delete this.playerExitedWitchspace;
	delete this.missionScreenOpportunity;
	delete this.playerBoughtNewShip;
	delete this.playerWillEnterWitchspace;
	mission.setInstructionsKey(null, "TCAT_missionScript");
	return;
}

//----------------------------------------------------------------------------------------
this.playerBoughtNewShip = function (ship) { // if player buys a new ship after the device is fitted, stop the mission
	if (missionVariables.TCAT_mission == "SNEAK"
		|| missionVariables.TCAT_mission == "CAUGHT"
		|| missionVariables.TCAT_mission == "INCOMING"
		|| missionVariables.TCAT_mission == "ARMADA"
		|| missionVariables.TCAT_mission == "REPELLED"
		|| missionVariables.TCAT_mission == "HUNT") {
		player.consoleMessage(expandMissionText("TCAT_naval_device_exploded"), 6);
		missionVariables.TCAT_mission = "CASE_CLOSED";
		this.cleanUp();
	}
}

//----------------------------------------------------------------------------------------
this.missionScreenOpportunity = function () {
	// next check if we have any conditions preventing the offering or continuing of the mission
	if (!player.ship.docked // we're in space
		|| player.score < 1500 // need 1500 kills to begin (for a little space between this and Thargoid Plans)
		|| galaxyNumber != 2 // we're not in G3
		|| !missionVariables.thargplans // Thargoid Plans mission never started
		|| missionVariables.thargplans != "MISSION_COMPLETE" // Thargoid Plans mission not completed
		|| missionVariables.TCAT_mission == "NOT_NOW" // player rejected mission and it's not time to re-offer yet
		|| (missionVariables.stealth_mission && missionVariables.stealth_mission != "OFFER" && missionVariables.stealth_mission != "CASE_CLOSED") // not at same time at stealth mission
		|| (Math.random() > 0.25 && missionVariables.TCAT_mission == "OFFER")) { // only 1 in 4 chance of initial offer anyway
		return;
	}

	if (player.ship.dockedStation.isMainStation && system.ID != 138) { // initial offering in system main station, as long as it's not Anenveza.
		switch (missionVariables.TCAT_mission) {
			case "OFFER": // make the initial offer
				mission.runScreen({ title: expandMissionText("TCAT_hide_sneak"), messageKey: "TCAT_initialOffer", choicesKey: "TCAT_choices", overlay: {name:"TCAT_navy_star.png", height:546}}, this.choice);
				break;
			case "REJECTED": // player said no
				missionVariables.TCAT_mission = "NOT_NOW";
				mission.setInstructionsKey(null, "TCAT_missionScript");
				missionVariables.TCAT_reOffer = -0.1;
				mission.runScreen({ title: expandMissionText("TCAT_unfortunate"), messageKey: "TCAT_rejected", overlay: {name:"TCAT_navy_star.png", height:546}});
				break;
			case "ACCEPTED": // player said yes
				missionVariables.TCAT_mission = "BRIEFING_1";
				mission.setInstructionsKey("TCAT_shortGoToStation", "TCAT_missionScript");
				mission.markSystem(138);
				mission.runScreen({ title: expandMissionText("TCAT_excellent"), messageKey: "TCAT_accepted", overlay: {name:"TCAT_navy_star.png", height:546}});
				break;
		}
		return;
	}

	if (system.ID == 138 && (missionVariables.TCAT_mission == "INCOMING" || missionVariables.TCAT_mission == "ARMADA") && system.countShipsWithRole("TCAT_mantis") == 0) {
		system.addShipsToRoute("TCAT_mantis", 1, 0.9, "sw");
		system.addShipsToRoute("TCAT_squadRaptor", 1, 0.75, "sw");
	}

	if (player.ship.dockedStation.hasRole("TCAT_navyStation")) {
		switch (missionVariables.TCAT_mission) { // offerings once player is at the navy station
			case "BRIEFING_1": // player accepted and went to military station - start sneak briefing
				missionVariables.TCAT_mission = "BRIEFING_2";
				mission.unmarkSystem(138);
				mission.runScreen({ title: expandMissionText("TCAT_briefing_title"), messageKey: "TCAT_briefing_1", overlay: {name:"TCAT_navy_star.png", height:546}});
				break;
			case "BRIEFING_2": // briefing second screen
				missionVariables.TCAT_mission = "BRIEFING_3";
				mission.runScreen({ title: expandMissionText("TCAT_briefing_prey"), messageKey: "TCAT_briefing_2", model: "TCAT_sneak" });
				break;
			case "BRIEFING_3": // briefing third screen
				if (!missionVariables.TCAT_missionBlock) {
					mission.setInstructionsKey("TCAT_shortHideAndSeek", "TCAT_missionScript");
					missionVariables.TCAT_missionBlock = true;
					missionVariables.TCAT_qDept = true; // make the equipment at the station available
					mission.runScreen({ title: expandMissionText("TCAT_goodluck"), messageKey: "TCAT_briefing_3", overlay: {name:"TCAT_navy_star.png", height:546}});
				}
				break;
			case "SNEAK": // less than 15 sneaks caught
				if (!missionVariables.TCAT_missionBlock) {
					missionVariables.TCAT_missionBlock = true;
					mission.runScreen({ title: expandMissionText("TCAT_more_work"), messageKey: "TCAT_sneak", overlay: {name:"TCAT_navy_star.png", height:546}});
				}
				break;
			case "CAUGHT": // 15 sneaks found, next briefing - interrupted by invasion fleet
				missionVariables.TCAT_mission = "INCOMING";
				mission.runScreen({ title: expandMissionText("TCAT_plan_revealed"), messageKey: "TCAT_caught", overlay: {name:"TCAT_navy_star.png", height:546}});
				this.warningSound.play()
				if (system.countShipsWithRole("TCAT_mantis") == 0) {
					system.addShipsToRoute("TCAT_mantis", 1, 0.9, "sw");
					system.addShipsToRoute("TCAT_squadRaptor", 1, 0.75, "sw");
				}
				break;
			case "INCOMING": // 15 sneaks found, next briefing - interrupted by invasion fleet
				if (!missionVariables.TCAT_missionBlock) {
					missionVariables.TCAT_missionBlock = true;
					mission.setInstructionsKey("TCAT_shortInvasion", "TCAT_missionScript");
					missionVariables.TCAT_mission = "ARMADA";
					player.ship.fuel += 7;
					mission.runScreen({ title: expandMissionText("TCAT_scramble"), messageKey: "TCAT_invasion", overlay: {name:"TCAT_navy_star.png", height:546}});
				}
				break;
			case "ARMADA": // if we're back before the invasion is over
				if (!missionVariables.TCAT_missionBlock) {
					player.ship.fuel += 7;
					mission.runScreen({ title: expandMissionText("TCAT_still_coming"), messageKey: "TCAT_armada", overlay: {name:"TCAT_navy_star.png", height:546}});
					missionVariables.TCAT_missionBlock = true;
				}
				break;
			case "REPELLED": // Invasion fleet repelled, time for the finale
				if (!missionVariables.TCAT_missionBlock) {
					mission.setInstructionsKey("TCAT_shortEndGame", "TCAT_missionScript");
					mission.markSystem(168);
					mission.runScreen({ title: expandMissionText("TCAT_endgame"), messageKey: "TCAT_repelled", overlay: {name:"TCAT_navy_star.png", height:546}});
					missionVariables.TCAT_mission = "HUNT";
					missionVariables.TCAT_missionBlock = true;
				}
				break;
			case "HUNT": // Left for the finale, but back before the kaboom?
				if (!missionVariables.TCAT_missionBlock) {
					mission.runScreen({ title: expandMissionText("TCAT_back_already"), messageKey: "TCAT_hunt", overlay: {name:"TCAT_navy_star.png", height:546}});
					missionVariables.TCAT_missionBlock = true;
				}
				break;
			case "SUCCESS": // Sneak station destroyed - job done
				missionVariables.TCAT_mission = "CASE_CLOSED";
				mission.setInstructionsKey(null, "TCAT_missionScript");
				mission.unmarkSystem(138);
				player.credits += 50000;
				player.bounty = 0;
				mission.runScreen({ title: expandMissionText("TCAT_mission_success"), messageKey: "TCAT_success", overlay: {name:"TCAT_navy_star.png", height:546}}, this.cleanUp);
				break;
		}
	}
}

//----------------------------------------------------------------------------------------
this.choice = function (choice) {
	switch (choice) {
		case "TCAT_1_ACCEPTED":
			missionVariables.TCAT_mission = "ACCEPTED";
			break;
		case "TCAT_2_REJECTED":
			missionVariables.TCAT_mission = "REJECTED";
			break;
	}
}

//----------------------------------------------------------------------------------------
this.shipLaunchedFromStation = function () {
	switch (missionVariables.TCAT_mission) {
		case "BRIEFING_2":
		case "BRIEFING_3":
		case "DISMISSED":
			// in case of forced launch during mission screen sequence
			missionVariables.TCAT_mission = "SNEAK";
			break;
	}
	missionVariables.TCAT_missionBlock = null;
}

//----------------------------------------------------------------------------------------
this.playerWillEnterWitchspace = function () {
	if ((missionVariables.TCAT_mission == "ARMADA") && galaxyNumber == 3 && system.ID == 138) { // if the player runs away during the armada attack
		missionVariables.TCAT_mission = "CASE_CLOSED";
		missionVariables.TCAT_navalStatus = "DEAD";
		this.cleanUp();
	}
}

//----------------------------------------------------------------------------------------
this.systemWillPopulate = function() {
	if (galaxyNumber == 2 && system.ID == 138 && missionVariables.TCAT_navalStatus == "ALIVE" && system.countShipsWithRole("TCAT_navyStation") == 0) {
		var stnPos = Vector3D(0, 0, 0.5).fromCoordinateSystem("swu");
		system.setPopulator("TCAT_navy", {
			callback: function (pos) {
				system.addShips("TCAT_navyStation", 1, pos, 0);
			},
			location: "COORDINATES",
			coordinates: stnPos,
			deterministic: true
		});
	}
	if (galaxyNumber == 2 && system.ID == 168 && missionVariables.TCAT_mission == "HUNT" && system.countShipsWithRole("TCAT_bugStation") == 0) {
		var stnPos = Vector3D(225000, 100000, -4000000);
		system.setPopulator("TCAT_bugstation", {
			callback: function (pos) {
				worldScripts.TCAT_missionScript.setUpBugStation(pos);
			},
			location: "COORDINATES",
			coordinates: stnPos,
			deterministic: true
		}) 
		return;
	}
}

//----------------------------------------------------------------------------------------
this.shipWillLaunchFromStation = function (station) { // first launch only
	if (station.isMainStation) {
		if (!missionVariables.TCAT_mission) { // set the mission up if it's not defined, but so it won't trigger on game start-up
			missionVariables.TCAT_mission = "OFFER"; 
		}
		this.shipExitedWitchspace();

		delete this.shipWillLaunchFromStation;
	}
}

//----------------------------------------------------------------------------------------
this.playerEnteredNewGalaxy = function (galaxyNumber) { // if we jump galaxies whilst mission is running or after rejection
	if (galaxyNumber == 3 && missionVariables.TCAT_mission != "OFFER") {
		missionVariables.TCAT_mission = "CASE_CLOSED";
		missionVariables.TCAT_navalStatus = "DEAD";
		this.cleanUp();
	}
}

//----------------------------------------------------------------------------------------
this.shipWillExitWitchspace = function () {
	if (system.isInterstellarSpace || galaxyNumber != 2) {
		return;
	}

	this.ambush = (System.infoForSystem(galaxyNumber, system.ID).routeToSystem(System.infoForSystem(galaxyNumber, 168)).route.length - 1) / 6;
	if (missionVariables.TCAT_mission == "HUNT" && (Math.random() > this.ambush)) {
		this.ambushDelay = Math.ceil(Math.random() * 6) + 4;
		this.ambushTimer = new Timer(this, function () { this.ambushPlayer(this.ambush); }, this.ambushDelay);
	}
}

//----------------------------------------------------------------------------------------
this.ambushPlayer = function (ambush) {
	//system.legacy_addShipsWithinRadius("TCAT_warship", (4 - Math.ceil(ambush * 3)), "abs", player.ship.position, 15000);
	system.addShips("TCAT_warship", (4 - Math.ceil(ambush * 3)), player.ship.position, 15000);
	player.consoleMessage(expandMissionText("TCAT_ambush"), 6);
}

//----------------------------------------------------------------------------------------
this.shipDockedWithStation = function (station) {
	if (station.hasRole("TCAT_navyStation")) {
		missionVariables.TCAT_navalEquipment = true;
	} else {
		missionVariables.TCAT_navalEquipment = false;
	}

}

//----------------------------------------------------------------------------------------
this.guiScreenChanged = function () {
	if (!player.ship.docked || !player.ship.dockedStation.hasRole("TCAT_navyStation")) { // if we're not at the navy station
		return;
	}

	// replace marketplace screen with exam offering mission screen
	if (guiScreen == "GUI_SCREEN_MARKET") {
		mission.runScreen({ title: expandMissionText("TCAT_tescoos"), messageKey: "TCAT_noTrading", overlay: {name:"TCAT_navy_star.png", height:546}, exitScreen: "GUI_SCREEN_STATUS" });
	}
}

//----------------------------------------------------------------------------------------
this.shipExitedWitchspace = function () {
	if (missionVariables.TCAT_mission == "NOT_NOW") {
		missionVariables.TCAT_reOffer += 0.01; // incremental 1% added chance per jump of re-offering the mission
		if (Math.random() < missionVariables.TCAT_reOffer) {
			missionVariables.TCAT_mission = "OFFER";
		}
	}

	if (system.isInterstellarSpace || system.sun.isGoingNova || system.sun.hasGoneNova || missionVariables.TCAT_mission != "SNEAK") { // stop the addition if interstellar space, system is going Nova, or if this part of the mission is not running.
		return;
	}

	this.sneakChance = 0.5 - ((system.techLevel + system.government) / 100);
	if (Math.random() < this.sneakChance) {
		system.addShipsToRoute("TCAT_sneak", 1);
		this.delayedMessage(expandMissionText("TCAT_sneak_detected"), 6, 5);
	}
}

//----------------------------------------------------------------------------------------
this.delayedMessage = function (messageString, duration, delay) {
	this.messageTimer = new Timer(this, function () { this.displayMessage(messageString, duration); }, delay);
}

//----------------------------------------------------------------------------------------
this.displayMessage = function (messageString, duration) {
	if (messageString) {
		if (!duration || duration < 1) {
			duration = 6;
		}
		player.consoleMessage(messageString, duration);
	}
}

//----------------------------------------------------------------------------------------
this.setUpBugStation = function (pos) {
	var xPos = pos.x;
	var yPos = pos.y;
	var zPos = pos.z;

	var bugb;
	//system.legacy_addShipsAtPrecisely("TCAT_bugStation", 1, "abs", [xPos, yPos, zPos]);
	bugb = system.addShips("TCAT_bugStation", 1, pos, 0);
	if (bugb && bugb.length > 0) bugb[0].suppressArrivalReports = true;
	//system.legacy_addShipsAtPrecisely("TCAT_bugBase", 1, "abs", [xPos - 2000, yPos, zPos + 1000]);
	bugb = system.addShips("TCAT_bugBase", 1, [xPos - 2000, yPos, zPos + 1000], 0);
	if (bugb && bugb.length > 0) bugb[0].suppressArrivalReports = true;
	//system.legacy_addShipsAtPrecisely("TCAT_bugBase", 1, "abs", [xPos + 2000, yPos, zPos + 1000]);
	bugb = system.addShips("TCAT_bugBase", 1, [xPos + 2000, yPos, zPos + 1000], 0);
	if (bugb && bugb.length > 0) bugb[0].suppressArrivalReports = true;
	//system.legacy_addShipsAtPrecisely("TCAT_bugBase", 1, "abs", [xPos + 2000, yPos, zPos - 24000]);
	bugb = system.addShips("TCAT_bugBase", 1, [xPos + 2000, yPos, zPos - 24000], 0);
	if (bugb && bugb.length > 0) bugb[0].suppressArrivalReports = true;
	//system.legacy_addShipsAtPrecisely("TCAT_bugBase", 1, "abs", [xPos - 2000, yPos, zPos - 24000]);
	bugb = system.addShips("TCAT_bugBase", 1, [xPos - 2000, yPos, zPos - 24000], 0);
	if (bugb && bugb.length > 0) bugb[0].suppressArrivalReports = true;
	//system.legacy_addShipsWithinRadius("TCAT_warship", 2, "abs", [xPos, yPos, zPos - 24000], 10000);
	system.addShips("TCAT_warship", 2, [xPos, yPos, zPos - 24000], 10000);

	//system.legacy_addShipsAtPrecisely("TCAT_jumpGate", 1, "abs", [xPos + 2000, yPos + 5000, zPos - 48000]); // far jump gate
	system.addShips("TCAT_jumpGate", 1, [xPos + 2000, yPos + 5000, zPos - 48000], 0);
	//system.legacy_addShipsAtPrecisely("TCAT_jumpGate", 1, "abs", [2000, 2000, -100000]); // near jump gate
	system.addShips("TCAT_jumpGate", 1, [2000, 2000, -100000], 0);

	//system.legacy_addShipsAtPrecisely("TCAT_navyBeacon", 1, "abs", [2500, 2500, -80000]); // jump gate marker buoy
	system.addShips("TCAT_navyBeacon", 1, [2500, 2500, -80000], 0);
	//system.legacy_addShipsAtPrecisely("TCAT_bugBase", 1, "abs", [4000, 4000, -98000]); // guard base near jump gate
	bugb = system.addShips("TCAT_bugBase", 1, [4000, 4000, -98000], 0);
	if (bugb && bugb.length > 0) bugb[0].suppressArrivalReports = true;
	//system.legacy_addShipsAtPrecisely("TCAT_raptor", 1, "abs", [300, 300, -15000]); // raptor flying about
	system.addShips("TCAT_raptor", 1, [300, 300, -15000], 0);

	this.gateRockCount = Math.ceil(Math.random() * 26) + 14; // Between 15 and 40 normal asteroids near the gate
	this.rockCount = Math.ceil(Math.random() * 26) + 94; // Between 95 and 120 normal asteroids
	this.gunCount = Math.floor(this.rockCount / 10); // Between 9 and 12 asteroids with hidden gun emplacements
	this.warshipCount = Math.ceil(Math.random() * 6) + 1; // Between 1 and 7 warships

	//system.legacy_addShipsWithinRadius("asteroid", this.gateRockCount, "abs", [xPos, yPos, zPos - 24000], 20000);
	system.addShips("asteroid", this.gateRockCount, [xPos, yPos, zPos - 24000], 20000);

	for (var asteroidCounter = 0; asteroidCounter < this.rockCount; asteroidCounter++) {
		this.spawnOffset = new Vector3D.randomDirection().multiply((Math.random() * 44000) + 6000);
		this.newPosition = this.spawnOffset.add([xPos, yPos, zPos]);
		//system.legacy_addShipsAtPrecisely("asteroid", 1, "abs", this.newPosition);
		system.addShips("asteroid", 1, this.newPosition, 0);
	}

	for (var towerCounter = 0; towerCounter < this.gunCount; towerCounter++) {
		this.spawnOffset = new Vector3D.randomDirection().multiply((Math.random() * 38000) + 12000);
		this.newPosition = this.spawnOffset.add([xPos, yPos, zPos]);
		//system.legacy_addShipsAtPrecisely("TCAT_gunTower", 1, "abs", this.newPosition);
		system.addShips("TCAT_gunTower", 1, this.newPosition, 0);
	}

	for (var shipCounter = 0; shipCounter < this.warshipCount; shipCounter++) {
		this.spawnOffset = new Vector3D.randomDirection().multiply((Math.random() * 38000) + 12000);
		this.newPosition = this.spawnOffset.add([xPos, yPos, zPos]);
		//system.legacy_addShipsAtPrecisely("TCAT_warship", 1, "abs", this.newPosition);
		system.addShips("TCAT_warship", 1, this.newPosition, 0);
	}

	this.spawnOffset = new Vector3D.randomDirection().multiply((Math.random() * 34000) + 6000);
	this.newPosition = this.spawnOffset.add([xPos, yPos, zPos]);
	//system.legacy_addShipsAtPrecisely("TCAT_controller5", 1, "abs", this.newPosition);
	system.addShips("TCAT_controller5", 1, this.newPosition, 0);
};
