"use strict";
this.name = "Caduceus Damage Control Node";
this.author = "Thargoid";
this.copyright = "Creative Commons Attribution - Non-Commercial - Share Alike 3.0 license";
this.description = "Damage Control system based on repair bots";
this.version = "2.0";

this.equipmentDamaged = function (equipment) {
	if (player.ship.equipmentStatus("EQ_DCN") == "EQUIPMENT_UNAVAILABLE") {
		return;
	}

	if (equipment == "EQ_DCN") {
		if (this.damageControlTimer && this.damageControlTimer.isRunning) {
			this.damageControlTimer.stop();
			delete this.damageControlTimer;
		}
		var repairTime = 60 + Math.ceil(Math.random() * 120);
		player.consoleMessage("DCN offline - entering self-repair mode", 6);
		this.selfRepairTimer = new Timer(this, this.selfRepair, repairTime);
	} else {
		if (!this.damageControlTimer || !this.damageControlTimer.isRunning) {
			var repairTime = 120 + Math.ceil(Math.random() * 180);
			player.consoleMessage("DCN activated", 6);
			this.damageControlTimer = new Timer(this, this.repairSystems, repairTime);
		}
	}
}

this.selfRepair = function () {
	if (player.ship.equipmentStatus("EQ_DCN") == "EQUIPMENT_UNAVAILABLE") {
		return;
	}

	if (Math.random() < 0.75) // 75% chance of self-repair
	{
		player.ship.setEquipmentStatus("EQ_DCN", "EQUIPMENT_OK");
		this.checkSystems();
		if (this.playerDamagedList.length > 0) {
			player.consoleMessage("DCN online and activated", 6);
			var repairTime = 120 + Math.ceil(Math.random() * 180);
			this.damageControlTimer = new Timer(this, this.repairSystems, repairTime);
		} else {
			player.consoleMessage("DCN online and in standby mode", 6);
		}
	} else {
		if (player.ship.equipmentStatus("EQ_DCN") == "EQUIPMENT_DAMAGED") // just in case it was repaired in the meantime
		{
			var repairTime = 60 + Math.ceil(Math.random() * 120);
			player.consoleMessage("DCN offline - self-repair continuing", 6);
			this.selfRepairTimer = new Timer(this, this.selfRepair, repairTime);
		}
	}
}

this.equipmentDestroyed = function (equipment) {
	if (equipment == "EQ_DCN") {
		this.stopTimers();
	}
}

this.stopTimers = this.shipWillDockWithStation = this.shipDied = function () {
	if (this.damageControlTimer && this.damageControlTimer.isRunning) {
		this.damageControlTimer.stop();
		delete this.damageControlTimer;
	}
	if (this.selfRepairTimer && this.selfRepairTimer.isRunning) {
		player.ship.setEquipmentStatus("EQ_DCN", "EQUIPMENT_OK");
		this.selfRepairTimer.stop();
		delete this.selfRepairTimer;
	}
}

this.shipWillLaunchFromStation = function () {
	if (player.ship.equipmentStatus("EQ_DCN") == "EQUIPMENT_OK") {
		this.checkSystems();
		if (this.playerDamagedList.length > 0) {
			var repairTime = 120 + Math.ceil(Math.random() * 180);
			player.consoleMessage("Repair system reactivated", 6);
			this.damageControlTimer = new Timer(this, this.repairSystems, repairTime);
		}
	} else {
		if (player.ship.equipmentStatus("EQ_DCN") == "EQUIPMENT_DAMAGED") {
			this.selfRepair();
			return;
		}
	}
}

this.checkSystems = function () //new, faster one from http://aegidian.org/bb/viewtopic.php?f=4&t=10842&start=30#p163024
{
	this.playerDamagedList = [];
	var equipment = player.ship.equipment
	var listCounter = 0; // reset the counter
	for (listCounter = 0; listCounter < equipment.length; listCounter++) {
		if (player.ship.equipmentStatus(equipment[listCounter].equipmentKey) !== "EQUIPMENT_DAMAGED") {
			continue
		}
		var scriptEqInfo = EquipmentInfo.infoForKey(equipment[listCounter].equipmentKey).scriptInfo;
		if ((scriptEqInfo.thargoidRepairBotChance === undefined ||
				isNaN(scriptEqInfo.thargoidRepairBotChance)) ||
			(!isNaN(scriptEqInfo.thargoidRepairBotChance) &&
				scriptEqInfo.thargoidRepairBotChance > 0)) {
			this.playerDamagedList.push(equipment[listCounter].equipmentKey); // if it's broke and fixable, add it to the list.
		}
	}
}

this.repairSystems = function () {
	this.checkSystems();
	if (this.playerDamagedList.length == 0) {
		player.consoleMessage("All systems nominal - DCN entering standby mode", 5);
		return;
	} else {
		var damagedEquipment = Math.floor(Math.random() * this.playerDamagedList.length); // pick a random element from the list...
		this.fixedItem = this.playerDamagedList[damagedEquipment]; // ...define the item...
		this.damagedItem = this.fixedItem + "_DAMAGED"; //...and it's damaged version
		this.fixedName = EquipmentInfo.infoForKey(this.fixedItem).name; // define it's screen name
		this.fixedTech = EquipmentInfo.infoForKey(this.fixedItem).effectiveTechLevel // tech level of the item
		if (EquipmentInfo.infoForKey(this.fixedItem).scriptInfo.thargoidRepairBotChance !== undefined && !isNaN(EquipmentInfo.infoForKey(this.fixedItem).scriptInfo.thargoidRepairBotChance)) {
			this.fixChance = EquipmentInfo.infoForKey(this.fixedItem).scriptInfo.thargoidRepairBotChance;
		} else {
			this.fixChance = 0.6;
		}
	}

	if (Math.random() < this.fixChance) {
		this.fixItem();
	} else {
		var repairTime = 120 + Math.ceil(Math.random() * 180);
		player.consoleMessage(this.fixedName + " is still offline - work continuing.", 5);
		this.damageControlTimer = new Timer(this, this.repairSystems, repairTime);
	}
}


this.fixItem = function () {
	player.ship.setEquipmentStatus(this.fixedItem, "EQUIPMENT_OK"); // and actually fix the thing!
	player.consoleMessage(this.fixedName + " regenerated and operational", 5)
	switch (this.fixedItem) // specific OXP equipment which need rebooting after fixing, or have other issues.
	{
		case "EQ_FRAME_FUEL_COLLECTOR": {
			if (worldScripts["Fuel Collector"]) {
				worldScripts["Fuel Collector"].shipLaunchedFromStation(); // restart the timers in it's world script
				break;
			}
		}
		case "EQ_FRAME_BOUNTY_SCANNER": {
			if (worldScripts["Bounty Scanner"]) {
				worldScripts["Bounty Scanner"].shipLaunchedFromStation(); // restart the timers in it's world script
				break;
			}
		}
		case "EQ_EEU": {
			if (worldScripts["Emergency Energy Unit"]) {
				worldScripts["Emergency Energy Unit"].shipLaunchedFromStation(); // restart the timers in it's world script
				break;
			}
		}
		case "EQ_ROCKHERMIT_SCANNER": {
			if (worldScripts["rockHermit_Locator"]) {
				if (worldScripts["rockHermit_Locator"].version == "1.2.3") {
					worldScripts["rockHermit_Locator"].shipLaunchedFromStation() // use the inbuild scripting of the OXP to restart it.
				} else {
					this.beacons = system.shipsWithPrimaryRole("rockbeacof"); // list the inactive beacons (no lights or "R" on compass) 
					if (this.beacons.length > 0) {
						for (let i = 0; i < this.beacons.length; i++) {
							if (oolite.compareVersion('1.73') <= 0) {
								this.beacons[i].position = this.beacons[i].position.multiply(100); //throw the rockbeacof into space... 
							} else {
								this.beacons[i].setPosition(this.beacons[i].position.multiply(100)); //throw the rockbeacof into space... 
							}

							this.beacons[i].explode(); //...and blow it up. 
						}
					}
					worldScripts["rockHermit_Locator"].buoy = "rockbeacon"
					worldScripts["rockHermit_Locator"].addBuoys() // no inactive beacons, so use original code to add active beacons. 
				}
				break;
			}
		}
	}
	if (this.playerDamagedList.length > 1) {
		var repairTime = 120 + Math.ceil(Math.random() * 180);
		player.consoleMessage("Repairs ongoing", 6);
		this.damageControlTimer = new Timer(this, this.repairSystems, repairTime);
	}

}