"use strict";
/*jslint white: true, onevar: true, browser: false, evil: true, undef: true, nomen: true, regexp: true, plusplus: true, bitwise: true, newcap: true, maxerr: 50, indent: 4 */

// Standard setup
this.name = "Diplomacy_WarZonesMissions";
this.author = "phkb, m4r35n357";
this.copyright = "© 2011, 2012 m4r35n357 (Ian Smith)";
this.licence = "Creative Commons: attribution, non-commercial, sharealike. 3.0";
this.description = "Warzone missions for Diplomacy Warzones";

// missions

//-------------------------------------------------------------------------------------------------------------
this.startUpComplete = function () {
	var gcm = worldScripts.GalCopBB_Missions;
	// add these mission types into the main control
	var list = [93, 94];
	gcm._availableMissionTypes = gcm._availableMissionTypes.concat(list);
}

//-------------------------------------------------------------------------------------------------------------
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, [93, 94]);
		for (var i = 0; i < list.length; i++) {
			if (list[i].data.missionType === 93 && list[i].destination === system.ID) {
				if (player.ship.equipmentStatus("EQ_GCM_PASSENGER_TRANSPORT") === "EQUIPMENT_OK" && list[i].expiry >= clock.adjustedSeconds) {
					list[i].arrivalReportText = expandDescription("[missionType93_arrivalReport_complete]", {
						payment: formatCredits(list[i].payment, false, true)
					});
				} else {
					list[i].arrivalReportText = expandDescription("[missionType93_arrivalReport_late]");
				}

				list[i].data.quantity = 1;
				bb.$updateBBMissionPercentage(list[i].ID, 1);
				gcm.$logMissionData(list[i].ID);
			}
			if (list[i].data.missionType === 94 && list[i].destination === system.ID) {
				if (player.ship.equipmentStatus("EQ_GCM_PATIENT_TRANSPORT") === "EQUIPMENT_OK" && list[i].expiry >= clock.adjustedSeconds) {
					list[i].arrivalReportText = expandDescription("[missionType94_arrivalReport_complete]", {
						payment: formatCredits(list[i].payment, false, true)
					});
				} else {
					list[i].arrivalReportText = expandDescription("[missionType94_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;

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

	if (!item) {
		log(this.name + ".debug", "!!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 93
	if (item.data.missionType === 93) {
		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 94
	if (item.data.missionType === 94) {
		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, "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 93 - passenger transport (shouldn't need this, but just in case)
	if (item.data.missionType === 93) {
		p.removeEquipment("EQ_GCM_PASSENGER_TRANSPORT");
	}

	// *** type 94 - patient transport (shouldn't need this, but just in case)
	if (item.data.missionType === 94) {
		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 === 94) {
			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 93 - patient transport
	if (item.data.missionType === 93) {
		player.ship.removeEquipment("EQ_GCM_PASSENGER_TRANSPORT");
	}
	// *** type 94 - patient transport
	if (item.data.missionType === 94) {
		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 === 93) {
		// we'll just remove this one
		player.ship.removeEquipment("EQ_GCM_PASSENGER_TRANSPORT");
		eq = "";
	}

	if (item.data.missionType === 94) {
		// 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);
}

//-------------------------------------------------------------------------------------------------------------
// 93 - refugee transport
this.$missionType93_Values = function $missionType93_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;
    var warActor = this.$warringWith(system.ID);
    if (warActor) {
        var destInf = worldScripts.DayDiplomacy_000_Engine.$getActors()[warActor];
        missionVariables.warzones_othersystem = destInf.name;
    } else {
        missionVariables.warzones_othersystem = "a nearby system";
    }
	return result;
}

//-------------------------------------------------------------------------------------------------------------
// 94 - emergency patient transport
this.$missionType94_Values = function $missionType94_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;
    var warActor = this.$warringWith(system.ID);
    if (warActor) {
        var destInf = worldScripts.DayDiplomacy_000_Engine.$getActors()[warActor];
        missionVariables.warzones_othersystem = destInf.name;
    } else {
        missionVariables.warzones_othersystem = "a nearby system";
    }
	return result;
}

//-------------------------------------------------------------------------------------------------------------
this.$warringSystem = function(systemID) {
    var we = worldScripts.DayDiplomacy_040_WarEngine;
    return we.$isSystemWarring(systemID);
}

//-------------------------------------------------------------------------------------------------------------
this.$safeSystem = function(systemID) {
    var we = worldScripts.DayDiplomacy_040_WarEngine;
    return !we.$isSystemWarring(systemID);
}

//-------------------------------------------------------------------------------------------------------------
this.$warringWith = function(systemID) {
    var actorId = worldScripts.DayDiplomacy_010_Systems.$retrieveActorFromSystem(galaxyNumber, systemID).id;
    var tmp = worldScripts.DayDiplomacy_040_WarEngine._a[actorId];
    if (typeof tmp == "undefined") return null;
    // get the first one
    return Object.keys(tmp)[0];
}
