/*
========================================================================
extraThargoids_sweeper.js

This file is part of the ExtraThargoids expansion pack.
Author: UK_Eliter
License: 2017 Creative Commons: attribution, non-commercial, sharealike.
========================================================================
*/


/*
-------------------
JSLINT: set options
-------------------
*/

/*jshint esversion: 6*/
/*jshint sub:true*/


this.name = "extraThargoids_sweeper";
this.author = "UK_Eliter";
this.copyright = "2014 Creative Commons: attribution, non-commercial, sharealike.";
this.licence = "CC-NC-SA 3";
this.description = "Script for Thargon sweepers";


/*
------------------
DEBUGGING SWITCHES
------------------
*/

//this.logging = true; // THIS SHOULD BE COMMENTED OUT WHEN NOT TESTING
//var consoleDebugMessages = false;


/*
--------------
VARIABLES etc.
--------------
*/

this.sweep = new SoundSource();
this.sweep.sound = "extraThargoids_sweep.ogg";

this.mediumSweep = new SoundSource();
this.mediumSweep.sound = "extraThargoids_mediumSweep.ogg";

this.quietSweep = new SoundSource();
this.quietSweep.sound = "extraThargoids_quietSweep.ogg";


/*
------------------------
JSHINT: start of wrapper
------------------------
*/

(function() {
	"use strict";


	/*
	--------------
	EVENT HANDLERS
	--------------
	*/

	this.shipSpawned = function() {
		// If the scanTimer does not exist, create it.
		// If it does exist, and it is not running, start it.
		// Then - as usual - remove the ship object created by this function.
		if (!this.$scanTimer) {
			this.$scanTimer = new Timer(this, this.$scan, 1, 2.8);
		} else if (!this.$scanTimer.isRunning) {
			this.$scanTimer.start();
		}
		delete this.shipSpawned;
	};

	this.shipDied = this.entityDestroyed = this.playerWillEnterWitchspace = function() {
		this.$deleteTimers();
	};


	/*
	------------
	CALLED BY AI
	------------
	*/

	this.$_incomingMissile = function() {
		// This run (only) by extraThargoids_sweeperAI
		if (this.$incomingMissileTimer) {
			if (this.$incomingMissileTimer.isRunning) {
				return;
			} else {
				this.$incomingMissileTimer.start();
			}
		} else {
			this.$incomingMissileTimer = new Timer(this, this.$incomingMissileActual, 0.2);
		}
	};

	this.$_validateTarget = function() {
		if (this.ship.target && !this.ship.target.isThargoid) {
			this.ship.reactToAIMessage("TARGET_VALID");
		} else {
			this.ship.reactToAIMessage("TARGET_INVALID");
		}
	};

	this.$_sophistatedBeligerentAttackResponse = function() {
		// = if has this missile type, fire it, else . .
		if (this.ship.fireMissile("EQ_THARGON") == null) {
			this.ship.reactToAIMessage("DO_ATTACK");
		}
	};

	this.$_checkForPossiblyFarThargoids = function() {
		var s = system.filteredEntities(this, this.$isBug, this.ship, 55000);
		if (s.length > 0) {
			this.ship.reactToAIMessage("TARGET_FOUND"); // AI does actual SETTING of the target
		} else if (s.length > 0) {
			this.ship.reactToAIMessage("NOTHING_FOUND");
		}
	};


	/*
	-------
	FILTERS
	-------
	*/

	this.$poppable = function(e) {
		return e.isShip && (e.isMissile || e.isMine);
	};

	this.$isBug = function(e) {
		return (e.isShip && e.isThargoid);
	};

	this.$isTarget = function(e) {
		return e.isShip && (e.isMissile || e.isMine) && e.primaryRole !== "EQ_BUGGLYMISSILE" && e.name !== "Thargoid Projectile";
	};


	/*
	-------
	GENERAL
	-------
	*/

	this.$scan = function() {
		/*
		MASSES:
			MM Hardened Missile: 114 (!)M
			Nexus premium warhead: 67ish
			mini-missile mass: 114
			intercept missile mass: 210.3
			q-bomb: 135
			normal mass: 1324
			hardhead mass: 1638
			TCAT_claw: 472.5
			TCAT_talon: 135
			s[c].hasRole("EQ_HARDENED_MISSILE") || s[c].hasRole("armoury_MMHardMissile" || s[c].hasRole("EQ_MISSILE")
		*/

		if (!this.ship) {
			return;
		}
		if (this.$incomingMissileTimer && this.$incomingMissileTimer.isRunning) {
			return;
		}
		this.ship.lightsActive = false; // turn them off, in case they've been turned on before
		if (this.ship.energy < 45) {
			return;
		}
		this.ship.energy -= 1; // merely scanning takes a bit of energy
		var s = system.filteredEntities(this, this.$isTarget, this.ship, 26000);
		var num = s.length;
		if (num === 0) {
			return;
		}

		// What follows  starts going through all ordinance at large, and stops when the sweeper detects one of those pieces (or when reaches end of list)
		var detected = false;
		var chance;
		var c = num;
		while (c--) {
			if (s[c].mass < 125) {
				chance = 0.05;
			} else {
				chance = 0.86;
			}
			if (this.ship.position.distanceTo(s[c]) < 15000) {
				chance += 0.12;
			}
			if (Math.random() <= chance) {
				detected = true;
				break;
			}
		}
		// if has been a detection, sweeper fires its special ECM . .
		if ((detected) && (this.ship.energy > 14)) {
			this.$actualSweep();
		}
	};

	this.$actualSweep = function() {
		this.ship.lightsActive = true;
		this.ship.energy -= 14; // takes more energy to destroy (or try to destroy, anyway) something
		var s = system.filteredEntities(this, this.$poppable, this.ship, 26000);
		var num = s.length;
		if (num > 0) {
			var c = num;
			var chance;
			while (c--) {
				// log("EXTRA", s[c].primaryRole);
				switch (s[c].primaryRole) {
					case "TCAT_talon":
						chance = 0.05;
						break;
					case "TCAT_claw":
						chance = 0.035;
						break;
					case "EQ_BUGGLYMISSILE":
						chance = 0.01;
						break;
					case "EQ_F3G_ANTISWEEP_MISSILE":
						chance = 0.02;
						break;
					default:
						chance = 0.97;
				}
				if (Math.random() <= chance) {
					var damage = 16 + (Math.ceil(Math.random() * 40));
					if (s[c].energy <= damage) {
						s[c].explode();
					} else {
						s[c].energy -= damage;
					}
				}
			}
		}
		if (!this.ship || !player.ship) {
			return;
		}
		var ps = player.ship; // for speed, but changes won't affect the original variable
		var distanceToPlayer = this.ship.position.distanceTo(ps);
		if (distanceToPlayer < 28000) {
			if (distanceToPlayer < 13000) {
				this.sweep.play();
				if (Math.random() > 0.83) {
					this.ship.commsMessage(expandDescription("[thargoid_curses]", ps));
				}
			} else if (distanceToPlayer < 17500) {
				this.mediumSweep.play();
				if (Math.random() > 0.9) {
					this.ship.commsMessage(expandDescription("[thargoid_curses]", ps));
				}
			} else {
				this.quietSweep.play();
				if (Math.random() > 0.95) {
					this.ship.commsMessage(expandDescription("[thargoid_curses]", ps));
				}
			}
		}
	};

	this.$incomingMissileActual = function $incomingMissileActual() {
		this.$incomingMissileTimer.stop();
		if (this.ship.energy > 14) {
			this.$actualSweep();
		} else {
			this.ship.reactToAIMessage("GO_FLEE");
		}
	};


	/*
	-------
	CLEANUP
	-------
	*/

	this.$deleteTimers = function() {
		this.$deleteIncomingMissileTimer();
		this.$deleteScanTimer();
	};

	this.$deleteIncomingMissileTimer = function() {
		if (!this.$incomingMissileTimer) {
			return;
		}
		if (this.$incomingMissileTimer.isRunning) {
			this.$incomingMissileTimer.stop();
		}
		delete this.$incomingMissileTimer;
	};

	this.$deleteScanTimer = function() {
		if (!this.$scanTimer) {
			return;
		}
		if (this.$scanTimer.isRunning) {
			this.$scanTimer.stop();
		}
		delete this.$scanTimer;
	};


	/*
	----------------------
	JSHINT: end of wrapper
	----------------------
	*/

}).call(this);

// EOF