"use strict";
this.name = "IR-sdf-transporter.js";
this.author = "Ramirez";
this.copyright = "November 2010";
this.description = "Ship script for transporters";
this.version = "2.0";

//-------------------------------------------------------------------------------------------------------------
this.shipSpawned = function () {
}

//-------------------------------------------------------------------------------------------------------------
this.shipDied = function () {
	if (missionVariables.IR_status == "IR_LOA_5") {
		++missionVariables.IR_lander_kill_count;

		if (missionVariables.IR_lander_kill_count == 8) {
			worldScripts["IR-mfd.js"].$updateMFD("IR_sdf_transport_report", null, null, expandMissionText("IR_sunray"));
			missionVariables.IR_lander_kill_count = null;
			missionVariables.IR_status = "IR_landers";
		}
	}
}

//-------------------------------------------------------------------------------------------------------------
this.shipBeingAttacked = function(whom) {
	var grp = worldScripts["IR-main-script.js"]._trans_group;
	for (var i = 0; i < grp.ships.length; i++) {
		if (!grp.ships[i].target) {
			grp.ships[i].target = whom;
			grp.ships[i].performAttack();
		}
	}
}

//-------------------------------------------------------------------------------------------------------------
this.locateLeader = function () {
	this.leaderArray = system.shipsWithRole("IR-sdf-imperator");
	if (this.leaderArray.length > 0) {
		this.ship.target = this.leaderArray[0];
		this.ship.reactToAIMessage("LEADER_FOUND");
	}
}

//-------------------------------------------------------------------------------------------------------------
this.checkLeaderDistance = function () {
	var leader = system.shipsWithPrimaryRole("IR-sdf-imperator")[0];
	this.leaderDistance = this.ship.position.distanceTo(leader);
	if (this.leaderDistance > 51200) { // if the escort is more than 2 scanner ranges from the player, move it just off-scanner
		let leaderDirection = leader.position.subtract(this.ship.position).direction();
		let newPosition = leader.position.subtract(leaderDirection.multiply(20000));
		if (oolite.compareVersion('1.73') <= 0) {
			this.ship.position = newPosition;
		} else {
			this.ship.setPosition(newPosition);
		}
		this.ship.reactToAIMessage("LEADER_MID");
		return;
	}

	if (this.leaderDistance < 25600) {
		this.ship.reactToAIMessage("LEADER_NEAR");
	} else {
		if (this.leaderDistance > 38400 || leader.speed > 2000) {
			this.ship.reactToAIMessage("LEADER_FAR");
		} else {
			this.ship.reactToAIMessage("LEADER_MID");
		}
	}
}