using System;
using RimWorld;
using Verse;
namespace BlaxZones
{
/// Package Orbital. Design: 1.0 "Orbital purchases land in the zone".
public static partial class DeliveryRouter
{
///
/// Replaces the single TradeUtility.SpawnDropPod(IntVec3, Map, Thing) call in
/// TradeShip.GiveSoldThingToPlayer (TradeShip.cs:199-207), same signature. With "Route orbital
/// trade" on, picks a cell through TryFindDropSpot(map, t, DeliverySource.Orbital, ...) and calls
/// TradeUtility.SpawnDropPod(cell, map, t); otherwise, when no zone fits or on any exception (logged
/// once), calls TradeUtility.SpawnDropPod(dropSpot, map, t) with the vanilla spot it was given.
/// Bought pawns and sale silver come through here too (Tradeable.cs:472-478, Tradeable_Pawn.cs:59);
/// the router refuses pawns, so they land at the vanilla spot.
///
public static void DeliverFromOrbit(IntVec3 dropSpot, Map map, Thing t)
{
try
{
if (BlaxZonesMod.S.routeOrbital
&& TryFindDropSpot(map, t, DeliverySource.Orbital, out IntVec3 cell)
&& cell.IsValid && cell.InBounds(map))
{
TradeUtility.SpawnDropPod(cell, map, t);
return;
}
}
catch (Exception e)
{
ZonesLog.Once("Orbital delivery", e);
if (!FreeForVanillaPod(t))
return;
}
TradeUtility.SpawnDropPod(dropSpot, map, t);
}
///
/// After a routed SpawnDropPod threw: true when the thing can go into vanilla's pod. False when
/// a spawned pod already carries it, so it is not lost and must not be dropped twice. A thing
/// left in the contents of a pod that never spawned is taken out first; adding it to a second
/// container while it still has a holder would fail and lose it.
///
private static bool FreeForVanillaPod(Thing t)
{
try
{
if (t == null || t.Destroyed)
return true;
if (t.SpawnedOrAnyParentSpawned)
return false;
t.holdingOwner?.Remove(t);
}
catch (Exception e)
{
ZonesLog.Once("Orbital delivery fallback", e);
}
return true;
}
}
}