"use strict";
this.name = "GalCopBB_Warzone";
this.author = "phkb";
this.copyright = "2018 phkb";
this.description = "Controls all civil warzone missions (90-99)";
this.license = "CC BY-NC-SA 4.0";

/*
	*90 - evacuate refugees
		>> have option of taking them to a anarchy/feudal system and selling them as slaves?
    *91 - transfer injured
	92 - import weapons
		limit to non-galcop stations? link to smugglers? make it a smuggling mission?

	define elements of civil war, so they can be referenced in text (eg "Free Raxxla Party", "Destroy All Thargoids Forever Group" )
*/

this._warSystems = []; // systems where there is civil war
this._galJump = false;

//-------------------------------------------------------------------------------------------------------------
this.startUpComplete = function () {
	this._warSystems = this.$findWarSystems();

	var gcm = worldScripts.GalCopBB_Missions;
	// add these mission types into the main control
	var list = [90, 91];
	gcm._availableMissionTypes = gcm._availableMissionTypes.concat(list);
}

//-------------------------------------------------------------------------------------------------------------
this.playerEnteredNewGalaxy = function (galaxyNumber) {
	this._warSystems = this.$findWarSystems();
	this._galJump = true;
}

//-------------------------------------------------------------------------------------------------------------
this.shipWillExitWitchspace = function () {
	if (this._galJump === true) {
		this._galJump = false;
		this._warSystems = this.$findWarSystems();
	}
}

//-------------------------------------------------------------------------------------------------------------
this.shipWillDockWithStation = function (station) {
	// check for other mission types being completed
	if (station.isMainStation) {
		var gcm = worldScripts.GalCopBB_Missions;
		var bb = worldScripts.BulletinBoardSystem;
		var list = gcm.$getListOfMissions(true, [90, 91]);
		for (var i = 0; i < list.length; i++) {
			if (list[i].data.missionType === 90 && list[i].destination === system.ID) {
				if (player.ship.equipmentStatus("EQ_GCM_PASSENGER_TRANSPORT") === "EQUIPMENT_OK" && list[i].expiry >= clock.adjustedSeconds) {
					list[i].arrivalReportText = expandDescription("[missionType90_arrivalReport_complete]", {
						payment: formatCredits(list[i].payment, false, true)
					});
				} else {
					list[i].arrivalReportText = expandDescription("[missionType90_arrivalReport_late]");
				}

				list[i].data.quantity = 1;
				bb.$updateBBMissionPercentage(list[i].ID, 1);
				gcm.$logMissionData(list[i].ID);
			}
			if (list[i].data.missionType === 91 && list[i].destination === system.ID) {
				if (player.ship.equipmentStatus("EQ_GCM_PATIENT_TRANSPORT") === "EQUIPMENT_OK" && list[i].expiry >= clock.adjustedSeconds) {
					list[i].arrivalReportText = expandDescription("[missionType91_arrivalReport_complete]", {
						payment: formatCredits(list[i].payment, false, true)
					});
				} else {
					list[i].arrivalReportText = expandDescription("[missionType91_arrivalReport_late]");
				}

				list[i].data.quantity = 1;
				bb.$updateBBMissionPercentage(list[i].ID, 1);
				gcm.$logMissionData(list[i].ID);
			}
		}
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$acceptedMission = function $acceptedMission(missID) {
	var bb = worldScripts.BulletinBoardSystem;
	var item = bb.$getItem(missID);
	var gcm = worldScripts.GalCopBB_Missions;

	if (this._debug) log(this.name, "accepted mission id = " + missID);

	if (!item) {
		log(this.name, "!!ERROR: BB returned null value from $getItem on mission ID " + missID);
		return;
	}
	gcm.$updateLastMissionDate(item.source, item.data.missionType);

	// give player passenger transport for mission type 90
	if (item.data.missionType === 90) {
		var eq = EquipmentInfo.infoForKey("EQ_GCM_PASSENGER_TRANSPORT");
		if (player.ship.cargoSpaceAvailable < eq.requiredCargoSpace) this.$freeCargoSpace(eq.requiredCargoSpace, "");
		player.ship.awardEquipment("EQ_GCM_PASSENGER_TRANSPORT");
	}
	
	// give player patient transport for mission type 91
	if (item.data.missionType === 91) {
		var eq = EquipmentInfo.infoForKey("EQ_GCM_PATIENT_TRANSPORT");
		if (player.ship.cargoSpaceAvailable < eq.requiredCargoSpace) this.$freeCargoSpace(eq.requiredCargoSpace, "");
		player.ship.awardEquipment("EQ_GCM_PATIENT_TRANSPORT");
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$completedMission = function $completedMission(missID) {
	var p = player.ship;
	var bb = worldScripts.BulletinBoardSystem;
	var item = bb.$getItem(missID);
	var gcm = worldScripts.GalCopBB_Missions;

	if ([90, 91].indexOf(item.data.missionType) >= 0) {
		// if the player has a bounty, doing these missions will reduce it
		if (player.ship.bounty > 0) {
			for (var i = 0; i < 5; i++) {
				if (player.ship.bounty > 0) player.ship.setBounty(player.ship.bounty - 1, expandDescription("[gcm_community_service]"));
			}
			player.ship.consoleMessage(expandDescription("[gcm_bounty_reduced]"));
		}
	}

	// update mission history
	gcm.$addMissionHistory(item.source, item.data.missionType, 1, 0);

	gcm.$checkForFollowupMission(item);

	// adjust reputation with entities
	var rep = worldScripts.GalCopBB_Reputation;
	if (rep._disabled === false) {
		rep.$adjustReputationSuccess(item.data.missionType, item.source, item.destination, item.percentComplete);
	}

	// *** type 90 - passenger transport (shouldn't need this, but just in case)
	if (item.data.missionType === 90) {
		p.removeEquipment("EQ_GCM_PASSENGER_TRANSPORT");
	}

	// *** type 91 - patient transport (shouldn't need this, but just in case)
	if (item.data.missionType === 91) {
		p.removeEquipment("EQ_GCM_PATIENT_TRANSPORT");
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$confirmCompleted = function $confirmCompleted(missID) {
	var p = player.ship;
	var result = "";
	var bb = worldScripts.BulletinBoardSystem;
	var item = bb.$getItem(missID);
	if (item) {
		// *** type 91 - patient transport
		if (item.data.missionType === 91) {
			var chk = p.equipmentStatus("EQ_GCM_PATIENT_TRANSPORT");
			if (chk !== "EQUIPMENT_OK" && chk !== "EQUIPMENT_DAMAGED") {
				result += (result === "" ? "" : "\n") + expandDescription("[gcm_patient_transport_not_found]");
			}
			if (chk === "EQUIPMENT_DAMAGED") {
				result += (result === "" ? "" : "\n") + expandDescription("[gcm_patient_transport_damaged]");
			}
		}
	}
	return result;
}

//-------------------------------------------------------------------------------------------------------------
this.$terminateMission = function $terminateMission(missID) {
	var bb = worldScripts.BulletinBoardSystem;
	var item = bb.$getItem(missID);
	var sbm = worldScripts.Smugglers_BlackMarket;
	var gcm = worldScripts.GalCopBB_Missions;

	// adjust reputation only when the terminatePenalty flag is set to true 
	if (item.data.terminatePenalty === true) {
		// update mission history
		gcm.$updateFailedHistoryReputation(item);
	}
	// *** type 90 - patient transport
	if (item.data.missionType === 90) {
		player.ship.removeEquipment("EQ_GCM_PASSENGER_TRANSPORT");
	}
	// *** type 91 - patient transport
	if (item.data.missionType === 91) {
		player.ship.removeEquipment("EQ_GCM_PATIENT_TRANSPORT");
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$failedMission = function $failedMission(missID) {
	var bb = worldScripts.BulletinBoardSystem;
	var sbm = worldScripts.Smugglers_BlackMarket;
	var gcm = worldScripts.GalCopBB_Missions;
	var eq = "";

	if (!sbm) {
		// if there's no blackmarket option, just remove the equipment
		this.$terminateMission(missID);
		return;
	}

	var item = bb.$getItem(missID);
	// update mission history
	gcm.$updateFailedHistoryReputation(item);

	if (item.data.missionType === 90) {
		// we'll just remove this one
		player.ship.removeEquipment("EQ_GCM_PASSENGER_TRANSPORT");
		eq = "";
	}

	if (item.data.missionType === 91) {
		// we'll just remove this one
		player.ship.removeEquipment("EQ_GCM_PATIENT_TRANSPORT");
		eq = "";
	}

	if (eq != "") gcm._equipmentFromFailedMissions.push({
		missionType: item.data.missionType,
		source: item.source,
		equip: eq,
		date: clock.adjustedSeconds
	});
}

//-------------------------------------------------------------------------------------------------------------
this.$updateManifestEntry = function $updateManifestEntry(missID) {
	var gcm = worldScripts.GalCopBB_Missions;
	gcm.$updateManifestEntry(missID);
}

//-------------------------------------------------------------------------------------------------------------
this.$missionAvailability = function $missionAvailability(missID, missType, origSysID) {
	return worldScripts.GalCopBB_Missions.$missionAvailability(missID, missType, origSysID);
}

//-------------------------------------------------------------------------------------------------------------
// 90 - refugee transport
this.$missionType90_Values = function $missionType90_Values(workTime, routeTime, routeDistance, destSysInfo) {
	var missValues = worldScripts.GalCopBB_CoreMissionValues;
    var result = {};
	result["quantity"] = 1;
	result["price"] = parseInt((parseInt(Math.random() * 50) + 75) / 10) * 10 + (7 - destSysInfo.government) * 20 + missValues.$calcDistanceBonus(routeDistance, 10);
	result["expiry"] = clock.adjustedSeconds + routeTime + 10000; 
	result["penalty"] = result.price / 2;
	return result;
}

//-------------------------------------------------------------------------------------------------------------
// 91 - emergency patient transport
this.$missionType91_Values = function $missionType91_Values(workTime, routeTime, routeDistance, destSysInfo) {
	var missValues = worldScripts.GalCopBB_CoreMissionValues;
    var result = {};
	result["quantity"] = 1;
	result["price"] = parseInt((parseInt(Math.random() * 50) + 75) / 10) * 10 + (7 - destSysInfo.government) * 20 + missValues.$calcDistanceBonus(routeDistance, 10);
	result["expiry"] = clock.adjustedSeconds + routeTime + 1600; // we want the time to be tight for the patient transport -- transit time + 10 mins
	result["penalty"] = result.price / 2;
	return result;
}

//-------------------------------------------------------------------------------------------------------------
// returns a list of sysInfos where civil war is present
this.$findWarSystems = function $findWarSystems() {
	return SystemInfo.filteredSystems(this, function (other) {
		return (other.description.indexOf(expandDescription("[gcm_desc_civilwar]")) >= 0);
	});
}
