"use strict";
this.name = "TCAT_claw";
this.author = "Thargoid";
this.copyright = "Creative Commons: attribution, non-commercial, sharealike with clauses - see readme.txt";
this.description = "Ship script for the claw mine";
this.version = "2.0";

//----------------------------------------------------------------------------------------
this.spawnTalons = function () {
	if (player.ship && player.ship.position && this.ship.position.distanceTo(player.ship.position) < 25600) {
		player.consoleMessage(expandMissionText("TCAT_mine_launched"));
	}

	this.talonCount = 4 + Math.ceil(Math.random() * 12);
	function allAlienShips(entity) { return entity.isShip && entity.scanClass == "CLASS_THARGOID" };
	function notThargons(entity) { return !entity.hasRole("thargon") && !entity.hasRole("tharglet") };
	var anyAlienShips = system.filteredEntities(this, allAlienShips, this.ship, 25600);
	var motherShips = anyAlienShips.filter(notThargons);

	var loopCounter = 0; // reset the counter
	for (loopCounter = 0; loopCounter < this.talonCount; loopCounter++) {
		var Talon = this.ship.spawnOne("TCAT_talon");
		this.xDistance = ((Math.random() * 10) - 5);
		this.yDistance = ((Math.random() * 10) - 5);
		this.zDistance = ((Math.random() * 10) - 5);
		Talon.position = this.ship.position.add([this.xDistance, this.yDistance, this.zDistance]);

		let launchVector = Talon.position.subtract(this.ship.position).direction(); // unit vector pointing away from the mine
		let angle = Talon.heading.angleTo(launchVector); // angle between current heading and target heading
		let cross = Talon.heading.cross(launchVector).direction(); // set the plane where we should rotate in
		Talon.orientation = Talon.orientation.rotate(cross, -angle);

		if (motherShips.length > 0) { // if we have Thargoid motherships around, target them in preference
			Talon.target = motherShips[Math.floor(Math.random() * motherShips.length)];
		} else {
			if (anyAlienShips.length > 0) { // if we have something to target
				Talon.target = anyAlienShips[Math.floor(Math.random() * anyAlienShips.length)];
			} else {
				Talon.explode(); // self destruct if nothing to target
			}
		}
	}
}