using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using HarmonyLib;
using Newtonsoft.Json;
using SuperFantasyKingdom;
using SuperFantasyKingdom.Buildings;
using SuperFantasyKingdom.Tavern;
using SuperFantasyKingdom.UI;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem.UI;
using UnityEngine.Localization.Components;
using UnityEngine.UI;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("WeeklyContracts")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+d965f8db9c4c70b090cbdf98cea0af290dee8ac3")]
[assembly: AssemblyProduct("WeeklyContracts")]
[assembly: AssemblyTitle("WeeklyContracts")]
[assembly: AssemblyVersion("0.1.0.0")]
namespace WeeklyContracts;
internal enum Stage
{
None,
Offered,
Active,
Earned,
Declined,
Expired,
Claimed,
Refunded
}
[Serializable]
internal sealed class Contract
{
internal const int Price = 6;
public string run;
public int offeredDay;
public int deadline;
public Stage stage;
public string[] rewards;
public string claimed;
public int paidType;
public OrderKind selected;
public OrderKind[] offers;
[NonSerialized]
private bool settling;
[NonSerialized]
private Func<int, string[], bool> checkpointReceipt;
[NonSerialized]
private string pendingChoice;
internal OrderTerms Terms => OrderTerms.Get(selected);
internal string OfferMessage => $"Choose one this morning. Deliver before nightfall on day {deadline}.";
internal Contract ForCheckpoint(int coins, string[] relics)
{
if (checkpointReceipt == null || !checkpointReceipt(coins, relics))
{
return this;
}
Contract obj = (Contract)MemberwiseClone();
obj.stage = Stage.Claimed;
obj.claimed = pendingChoice;
return obj;
}
internal bool AtDawn(int day)
{
Advance(day, morning: true, night: false);
if (day < 1 || day > 28 || day <= deadline || stage == Stage.Earned)
{
return false;
}
offeredDay = day;
deadline = (day + 6) / 7 * 7;
stage = Stage.Offered;
rewards = null;
claimed = null;
paidType = 0;
selected = OrderKind.Bread;
offers = null;
return true;
}
internal void Advance(int day, bool morning, bool night)
{
if (stage == Stage.Offered && (day != offeredDay || !morning))
{
stage = Stage.Expired;
}
if (stage == Stage.Active && (day > deadline || (day == deadline && night)))
{
stage = Stage.Expired;
}
}
internal void Decide(bool accept)
{
if (stage == Stage.Offered)
{
stage = (accept ? Stage.Active : Stage.Declined);
}
}
internal bool Accept(OrderKind kind)
{
if (stage != Stage.Offered || offers == null || !offers.Contains(kind))
{
return false;
}
selected = kind;
stage = Stage.Active;
return true;
}
internal bool Deliver(string[] choices, Func<bool> spend, int material = 0)
{
if (stage != Stage.Active || (Terms.Coins == 0 && (choices == null || choices.Length != 3 || choices.Any(string.IsNullOrEmpty) || choices.Distinct().Count() != 3)))
{
return false;
}
if (settling)
{
return false;
}
settling = true;
try
{
if (!spend())
{
return false;
}
rewards = ((Terms.Coins == 0) ? choices : null);
paidType = material;
stage = Stage.Earned;
return true;
}
finally
{
settling = false;
}
}
internal bool Collect(string id, string savedName, Action grant, Func<bool> ownsTarget, Action<Exception> warn)
{
if (settling || stage != Stage.Earned || Terms.Coins != 0 || rewards == null || !rewards.Contains(id) || ownsTarget())
{
return false;
}
return SettleReward(id, grant, ownsTarget, (int _, string[] relics) => relics?.Contains(savedName) ?? false, warn);
}
internal bool CollectCoins(Func<int> balance, Action<int> credit, Action<Exception> warn)
{
if (settling || stage != Stage.Earned || Terms.Coins <= 0)
{
return false;
}
int amount = Terms.Coins;
long expected = (long)balance() + (long)amount;
return SettleReward(null, delegate
{
credit(amount);
}, () => balance() >= expected, (int coins, string[] _) => coins >= expected, warn);
}
private bool SettleReward(string choice, Action grant, Func<bool> received, Func<int, string[], bool> savedReceipt, Action<Exception> warn)
{
settling = true;
pendingChoice = choice;
checkpointReceipt = savedReceipt;
try
{
try
{
grant();
}
catch (Exception obj)
{
warn(obj);
}
if (!received())
{
return false;
}
claimed = choice;
stage = Stage.Claimed;
return true;
}
finally
{
checkpointReceipt = null;
pendingChoice = null;
settling = false;
}
}
internal bool Refund(Func<string, bool> available, Func<bool> restore)
{
if (settling || stage != Stage.Earned || Terms.Coins != 0 || (rewards != null && rewards.Any(available)))
{
return false;
}
settling = true;
try
{
if (!restore())
{
return false;
}
stage = Stage.Refunded;
return true;
}
finally
{
settling = false;
}
}
}
internal static class ContractCards
{
private const float RowHeight = 82f;
private static readonly Color Ink = Color32.op_Implicit(new Color32((byte)39, (byte)26, (byte)30, byte.MaxValue));
private static float Width => Mathf.Clamp((float)Screen.width / SettingsManager.Instance.GetUIScaling() - 80f, 340f, 510f);
internal static void Heading(UIOverlayMessage page, string title)
{
//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
TextMeshProUGUI component = ((Component)((Component)page).transform.Find("Message")).GetComponent<TextMeshProUGUI>();
float width = Width;
((Component)component).GetComponent<LayoutElement>().preferredWidth = width;
((TMP_Text)component).rectTransform.SetSizeWithCurrentAnchors((Axis)0, width);
VerticalLayoutGroup component2 = ((Component)page).GetComponent<VerticalLayoutGroup>();
((LayoutGroup)component2).childAlignment = (TextAnchor)1;
((HorizontalOrVerticalLayoutGroup)component2).spacing = 6f;
Transform val = ((Component)OverlayManager.Instance).transform.Find("Overlay/SizeSelection/HeaderContainer/Header");
if ((Object)(object)val == (Object)null)
{
((TMP_Text)component).text = title + "\n" + ((TMP_Text)component).text;
return;
}
RectTransform val2 = Block("Contract heading", ((Component)page).transform, width, 46f);
((Transform)val2).SetAsFirstSibling();
RectTransform val3 = (RectTransform)Object.Instantiate<Transform>(val, (Transform)(object)val2, false);
((Component)val3).gameObject.SetActive(true);
val3.anchorMin = Vector2.zero;
val3.anchorMax = Vector2.one;
Vector2 offsetMin = (val3.offsetMax = Vector2.zero);
val3.offsetMin = offsetMin;
TextMeshProUGUI component3 = ((Component)((Transform)val3).Find("Text")).GetComponent<TextMeshProUGUI>();
LocalizeStringEvent component4 = ((Component)component3).GetComponent<LocalizeStringEvent>();
if ((Object)(object)component4 != (Object)null)
{
((Behaviour)component4).enabled = false;
}
((TMP_Text)component3).text = title;
Graphic[] componentsInChildren = ((Component)val3).GetComponentsInChildren<Graphic>();
for (int i = 0; i < componentsInChildren.Length; i++)
{
componentsInChildren[i].raycastTarget = false;
}
}
private static RectTransform Block(string name, Transform parent, float width, float height)
{
//IL_0021: Unknown result type (might be due to invalid IL or missing references)
//IL_002b: Unknown result type (might be due to invalid IL or missing references)
//IL_0030: Unknown result type (might be due to invalid IL or missing references)
//IL_0038: Unknown result type (might be due to invalid IL or missing references)
//IL_003b: Unknown result type (might be due to invalid IL or missing references)
//IL_0045: Unknown result type (might be due to invalid IL or missing references)
//IL_006b: Expected O, but got Unknown
RectTransform val = (RectTransform)new GameObject(name, new Type[2]
{
typeof(RectTransform),
typeof(LayoutElement)
}).transform;
((Transform)val).SetParent(parent, false);
val.sizeDelta = new Vector2(width, height);
LayoutElement component = ((Component)val).GetComponent<LayoutElement>();
float minWidth = (component.preferredWidth = width);
component.minWidth = minWidth;
minWidth = (component.preferredHeight = height);
component.minHeight = minWidth;
return val;
}
private static RectTransform Box(string name, Transform parent, float x, float y, float width, float height)
{
//IL_0014: Unknown result type (might be due to invalid IL or missing references)
//IL_001e: Unknown result type (might be due to invalid IL or missing references)
//IL_0023: Unknown result type (might be due to invalid IL or missing references)
//IL_002b: Unknown result type (might be due to invalid IL or missing references)
//IL_002c: Unknown result type (might be due to invalid IL or missing references)
//IL_002d: Unknown result type (might be due to invalid IL or missing references)
//IL_003f: Unknown result type (might be due to invalid IL or missing references)
//IL_0045: Unknown result type (might be due to invalid IL or missing references)
//IL_0046: Unknown result type (might be due to invalid IL or missing references)
//IL_0047: Unknown result type (might be due to invalid IL or missing references)
//IL_004d: Unknown result type (might be due to invalid IL or missing references)
//IL_0053: Unknown result type (might be due to invalid IL or missing references)
//IL_0057: Unknown result type (might be due to invalid IL or missing references)
//IL_0061: Unknown result type (might be due to invalid IL or missing references)
//IL_0066: Unknown result type (might be due to invalid IL or missing references)
//IL_0071: Expected O, but got Unknown
RectTransform val = (RectTransform)new GameObject(name, new Type[1] { typeof(RectTransform) }).transform;
((Transform)val).SetParent(parent, false);
Vector2 val2 = default(Vector2);
((Vector2)(ref val2))..ctor(0f, 1f);
val.pivot = val2;
Vector2 anchorMin = (val.anchorMax = val2);
val.anchorMin = anchorMin;
val.anchoredPosition = new Vector2(x, 0f - y);
val.sizeDelta = new Vector2(width, height);
return val;
}
private static void Label(RectTransform rect, TextMeshProUGUI native, string value, float size, bool right = false)
{
//IL_0024: Unknown result type (might be due to invalid IL or missing references)
TextMeshProUGUI obj = ((Component)rect).gameObject.AddComponent<TextMeshProUGUI>();
((TMP_Text)obj).font = ((TMP_Text)native).font;
((TMP_Text)obj).fontSharedMaterial = ((TMP_Text)native).fontSharedMaterial;
((Graphic)obj).color = Ink;
float fontSize = (((TMP_Text)obj).fontSizeMax = size);
((TMP_Text)obj).fontSize = fontSize;
((TMP_Text)obj).fontSizeMin = 14f;
((TMP_Text)obj).enableAutoSizing = true;
((TMP_Text)obj).enableWordWrapping = true;
((TMP_Text)obj).alignment = (TextAlignmentOptions)(right ? 4100 : 4097);
((Graphic)obj).raycastTarget = false;
((TMP_Text)obj).text = value;
}
private static void Icon(RectTransform rect, Sprite sprite)
{
if (!((Object)(object)sprite == (Object)null))
{
Image obj = ((Component)rect).gameObject.AddComponent<Image>();
obj.sprite = sprite;
obj.preserveAspect = true;
((Graphic)obj).raycastTarget = false;
}
}
internal static Button Order(UIOverlayMessage page, Button native, OrderKind kind, int deadline, bool selectable)
{
//IL_0017: Unknown result type (might be due to invalid IL or missing references)
//IL_001c: Unknown result type (might be due to invalid IL or missing references)
//IL_007e: Unknown result type (might be due to invalid IL or missing references)
//IL_0085: Expected O, but got Unknown
//IL_0097: Unknown result type (might be due to invalid IL or missing references)
//IL_0181: Unknown result type (might be due to invalid IL or missing references)
//IL_0186: Unknown result type (might be due to invalid IL or missing references)
//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
//IL_00e9: Unknown result type (might be due to invalid IL or missing references)
//IL_0101: Unknown result type (might be due to invalid IL or missing references)
//IL_0106: Unknown result type (might be due to invalid IL or missing references)
//IL_0125: Unknown result type (might be due to invalid IL or missing references)
//IL_012a: Unknown result type (might be due to invalid IL or missing references)
//IL_012f: Unknown result type (might be due to invalid IL or missing references)
//IL_0130: Unknown result type (might be due to invalid IL or missing references)
//IL_0137: Unknown result type (might be due to invalid IL or missing references)
//IL_0151: Unknown result type (might be due to invalid IL or missing references)
//IL_0156: Unknown result type (might be due to invalid IL or missing references)
//IL_0162: Unknown result type (might be due to invalid IL or missing references)
//IL_02bb: Unknown result type (might be due to invalid IL or missing references)
//IL_02e5: Unknown result type (might be due to invalid IL or missing references)
OrderTerms orderTerms = OrderTerms.Get(kind);
ResourceData val = Kingdom.Material(kind);
string arg = (Kingdom.Supported(val) ? val.GetName() : ((object)orderTerms.Slot/*cast due to .constrained prefix*/).ToString());
float width = Width;
RectTransform val2 = Block(orderTerms.Title, ((Component)page).transform, width, 82f);
((Transform)val2).SetSiblingIndex(((Component)native).transform.parent.GetSiblingIndex());
Image val3 = ((Component)val2).gameObject.AddComponent<Image>();
Image val4 = (Image)((Selectable)native).targetGraphic;
val3.sprite = val4.sprite;
val3.type = val4.type;
val3.pixelsPerUnitMultiplier = val4.pixelsPerUnitMultiplier;
((Graphic)val3).raycastTarget = selectable;
Button val5 = (selectable ? ((Component)val2).gameObject.AddComponent<Button>() : null);
if ((Object)(object)val5 != (Object)null)
{
((Selectable)val5).targetGraphic = (Graphic)(object)val3;
ColorBlock colors = ((Selectable)native).colors;
((ColorBlock)(ref colors)).normalColor = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)243, (byte)213, byte.MaxValue));
Color selectedColor = (((ColorBlock)(ref colors)).highlightedColor = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)196, (byte)80, byte.MaxValue)));
((ColorBlock)(ref colors)).selectedColor = selectedColor;
((ColorBlock)(ref colors)).pressedColor = Color32.op_Implicit(new Color32((byte)235, (byte)157, (byte)65, byte.MaxValue));
((Selectable)val5).colors = colors;
}
else
{
((Graphic)val3).color = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)243, (byte)213, byte.MaxValue));
}
TextMeshProUGUI component = ((Component)((Component)native).transform.Find("Text")).GetComponent<TextMeshProUGUI>();
float num = width * 0.5f;
Label(Box("Job", (Transform)(object)val2, 14f, 4f, num + 5f, 32f), component, orderTerms.Title, 29f);
Label(Box("Deadline", (Transform)(object)val2, num + 22f, 4f, num - 36f, 32f), component, $"{orderTerms.Difficulty} / Night {deadline}", 24f, right: true);
Icon(Box("Delivery icon", (Transform)(object)val2, 14f, 39f, 32f, 32f), ((Object)(object)val != (Object)null) ? val.icon : null);
Label(Box("Delivery", (Transform)(object)val2, 54f, 36f, num - 62f, 38f), component, $"{orderTerms.Quantity} {arg}", 29f);
ResourceType val7 = (ResourceType)((orderTerms.Coins > 0) ? 12 : 28);
Icon(Box("Reward icon", (Transform)(object)val2, num + 6f, 39f, 32f, 32f), RaceManager.Instance.GetResourceIcon(val7));
Label(Box("Reward", (Transform)(object)val2, num + 46f, 36f, num - 58f, 38f), component, (orderTerms.Coins > 0) ? orderTerms.Reward : "Pick 1 of 3 relics", 27f);
return val5;
}
internal static void RelicArt(UIOverlayMessage page, Sprite sprite)
{
if (!((Object)(object)sprite == (Object)null))
{
RectTransform obj = Block("Relic artwork", ((Component)page).transform, 48f, 48f);
((Transform)obj).SetSiblingIndex(((Component)page).transform.Find("Message").GetSiblingIndex());
Icon(obj, sprite);
}
}
}
internal static class Kingdom
{
internal static ResourceData Bread => RaceManager.Instance.GetResourceData((ResourceType)9);
internal static ResourceData Material(OrderKind kind)
{
//IL_000b: Unknown result type (might be due to invalid IL or missing references)
return RaceManager.Instance.GetResourceData(OrderTerms.Get(kind).Slot);
}
internal static OrderKind[] Offers(int day)
{
//IL_0041: Unknown result type (might be due to invalid IL or missing references)
//IL_009f: Unknown result type (might be due to invalid IL or missing references)
//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
OrderKind[] array = new OrderKind[6]
{
OrderKind.Timber,
OrderKind.Stone,
OrderKind.Boards,
OrderKind.Grain,
OrderKind.Fish,
OrderKind.Water
};
List<OrderKind> list = new List<OrderKind>();
HashSet<ResourceType> hashSet = new HashSet<ResourceType>();
ResourceData bread = Bread;
bool flag = Supported(bread) && Choices().Length == 3;
if (flag)
{
hashSet.Add(bread.type);
}
int num = Math.Max(0, day - 1) / 7 * 2;
for (int i = 0; i < array.Length; i++)
{
if (list.Count >= 2)
{
break;
}
OrderKind orderKind = array[(num + i) % array.Length];
ResourceData val = Material(orderKind);
int quantity = OrderTerms.Get(orderKind).Quantity;
if (Supported(val) && Stock(val) >= quantity && ResourceManager.Instance.CanBeBuilt(new ResourceAmount(val.type, quantity)) && hashSet.Add(val.type))
{
list.Add(orderKind);
}
}
if (flag)
{
list.Add(OrderKind.Bread);
}
return list.ToArray();
}
internal static bool Supported(ResourceData food)
{
//IL_000a: Unknown result type (might be due to invalid IL or missing references)
//IL_0012: Unknown result type (might be due to invalid IL or missing references)
//IL_001c: Invalid comparison between Unknown and I4
if ((Object)(object)food != (Object)null && (int)food.type != 0)
{
return (int)food.buildingToTakeFrom != 666;
}
return false;
}
internal static ResourceData PaidFood(Contract contract)
{
//IL_0012: Unknown result type (might be due to invalid IL or missing references)
//IL_002f: Unknown result type (might be due to invalid IL or missing references)
//IL_0022: Unknown result type (might be due to invalid IL or missing references)
//IL_0027: Unknown result type (might be due to invalid IL or missing references)
//IL_003f: Unknown result type (might be due to invalid IL or missing references)
//IL_0044: Unknown result type (might be due to invalid IL or missing references)
ResourceType val = (ResourceType)((contract.paidType == 0) ? 9 : contract.paidType);
ResourceData val2 = Bread;
if (!Supported(val2) || val2.type != val)
{
val2 = RaceManager.Instance.GetResourceData(val);
}
if (!Supported(val2) || val2.type != val)
{
return null;
}
return val2;
}
private static IEnumerable<ResourcePacket> FreePackets(ResourceStorage storage, ResourceType type)
{
//IL_0007: Unknown result type (might be due to invalid IL or missing references)
//IL_0008: Unknown result type (might be due to invalid IL or missing references)
return from p in storage.GetAllResourcePackets()
where p != null && p.GetResourceType() == type && !p.IsReserved() && p.GetAmount() > 0
select p;
}
internal static int Stock(ResourceData food)
{
//IL_0016: Unknown result type (might be due to invalid IL or missing references)
//IL_0031: Unknown result type (might be due to invalid IL or missing references)
//IL_0060: Unknown result type (might be due to invalid IL or missing references)
//IL_0051: Unknown result type (might be due to invalid IL or missing references)
//IL_0093: Unknown result type (might be due to invalid IL or missing references)
if (!Supported(food))
{
return 0;
}
ResourceManager instance = ResourceManager.Instance;
BuildingCity building = CityManager.Instance.GetBuilding(food.buildingToTakeFrom);
int value;
if ((Object)(object)building == (Object)null)
{
instance.GetStartingResourcesDictionary().TryGetValue(food.type, out value);
}
else
{
ResourceStorage storage = ((Building)building).GetStorage();
value = (storage.ShouldGenerateResourcePackets() ? FreePackets(storage, food.type).Sum((ResourcePacket p) => p.GetAmount()) : storage.GetResourceQuantity(food.type, false));
}
return Math.Max(0, Math.Min(value, instance.GetResourceAvailableAmount(food.type, false)));
}
internal static bool Spend(ResourceData food, int quantity = 6)
{
//IL_000f: Unknown result type (might be due to invalid IL or missing references)
//IL_0015: Unknown result type (might be due to invalid IL or missing references)
//IL_0029: Unknown result type (might be due to invalid IL or missing references)
//IL_004a: Unknown result type (might be due to invalid IL or missing references)
//IL_004f: Unknown result type (might be due to invalid IL or missing references)
//IL_0053: Unknown result type (might be due to invalid IL or missing references)
//IL_0057: Unknown result type (might be due to invalid IL or missing references)
//IL_008f: Unknown result type (might be due to invalid IL or missing references)
//IL_0078: Unknown result type (might be due to invalid IL or missing references)
//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
if (Stock(food) < quantity || !ResourceManager.Instance.CanBeBuilt(new ResourceAmount(food.type, quantity)))
{
return false;
}
BuildingCity building = CityManager.Instance.GetBuilding(food.buildingToTakeFrom);
if ((Object)(object)building == (Object)null)
{
ResourceManager.Instance.GetStartingResourcesDictionary()[food.type] -= quantity;
return true;
}
ResourceStorage storage = ((Building)building).GetStorage();
if (!storage.ShouldGenerateResourcePackets())
{
storage.RemoveResourceWithoutPackage(food.type, quantity);
return true;
}
List<ResourcePacket> list = new List<ResourcePacket>();
int num = quantity;
ResourcePacket[] array = FreePackets(storage, food.type).ToArray();
foreach (ResourcePacket val in array)
{
if (val.IsReserved())
{
continue;
}
ResourcePacket val2 = storage.TakeResourcePacket(val.GetIdentifier(), false);
if (val2 == null)
{
continue;
}
list.Add(val2);
num -= val2.GetAmount();
if (num <= 0)
{
if (num < 0)
{
storage.GenerateResource(food.type, -num);
}
return true;
}
}
foreach (ResourcePacket item in list)
{
storage.AddResourcePacket(item, false);
}
return false;
}
internal static bool Deliver(Contract contract, ResourceData food)
{
//IL_004e: Unknown result type (might be due to invalid IL or missing references)
//IL_0058: Expected I4, but got Unknown
//IL_0067: Unknown result type (might be due to invalid IL or missing references)
OrderTerms terms = contract.Terms;
if (!Supported(food) || !contract.Deliver((terms.Coins == 0) ? Choices() : null, () => Spend(food, terms.Quantity), (int)food.type))
{
return false;
}
ResourceManager.Instance.ResourceAmountChanged(food.type);
return true;
}
internal static bool ReturnPayment(Contract contract)
{
//IL_003f: Unknown result type (might be due to invalid IL or missing references)
ResourceData food = PaidFood(contract);
if (!contract.Refund(CanClaim, () => Refund(food)))
{
return false;
}
ResourceManager.Instance.ResourceAmountChanged(food.type);
return true;
}
internal static bool Refund(ResourceData food)
{
//IL_0010: Unknown result type (might be due to invalid IL or missing references)
//IL_003e: Unknown result type (might be due to invalid IL or missing references)
//IL_0044: Unknown result type (might be due to invalid IL or missing references)
//IL_002b: Unknown result type (might be due to invalid IL or missing references)
if (!Supported(food))
{
return false;
}
BuildingCity building = CityManager.Instance.GetBuilding(food.buildingToTakeFrom);
if ((Object)(object)building != (Object)null)
{
((Building)building).GetStorage().GenerateResource(food.type, 6);
}
else
{
ResourceManager.Instance.RegisterStartingResource(new ResourceAmount(food.type, 6));
}
return true;
}
private static bool Eligible(string id)
{
//IL_0069: Unknown result type (might be due to invalid IL or missing references)
//IL_006e: Unknown result type (might be due to invalid IL or missing references)
//IL_0077: Unknown result type (might be due to invalid IL or missing references)
//IL_007a: Invalid comparison between Unknown and I4
//IL_007c: Unknown result type (might be due to invalid IL or missing references)
//IL_0082: Unknown result type (might be due to invalid IL or missing references)
if (string.IsNullOrEmpty(id) || !RewardPolicy.Allows(id))
{
return false;
}
Relic relic = AddressablesManager.Instance.GetRelic(id);
RelicManager instance = RelicManager.Instance;
if ((Object)(object)relic == (Object)null || ((Item)relic).GetIdentifier() != id || !instance.IsUnlocked(id) || relic.IsLaw() || relic.IsRacial() || relic.GetRequiredKingdomLevel() > RaceDataManager.Instance.GetKingdomLevel())
{
return false;
}
Races kingdom = ((Item)relic).GetKingdom();
if (!relic.IsGeneric() && (int)kingdom != 11 && kingdom != RaceManager.Instance.GetRace())
{
return false;
}
string relatedUnit = relic.GetRelatedUnit();
if (string.IsNullOrEmpty(relatedUnit) || (Object)(object)UnitManager.Instance.GetUnit(relatedUnit) != (Object)null)
{
return instance.CanAddRelic(id);
}
return false;
}
private static HashSet<string> Upgrades()
{
return (from r in AddressablesManager.Instance.GetAllRelics().Values
where (Object)(object)r != (Object)null && (Object)(object)r.GetUpgrade() != (Object)null
select ((Item)r.GetUpgrade()).GetIdentifier()).ToHashSet();
}
internal static Relic ClaimTarget(string id)
{
if (Upgrades().Contains(id) || !Eligible(id))
{
return null;
}
RelicManager instance = RelicManager.Instance;
if (!instance.HasRelic(id))
{
return AddressablesManager.Instance.GetRelic(id);
}
Relic relic = instance.GetRelic(id);
Relic val = (((Object)(object)relic != (Object)null) ? relic.GetUpgrade() : null);
if ((Object)(object)val == (Object)null)
{
return null;
}
string identifier = ((Item)val).GetIdentifier();
if (!Eligible(identifier) || instance.HasRelic(identifier) || !((Object)(object)AddressablesManager.Instance.GetRelic(identifier) == (Object)(object)val))
{
return null;
}
return val;
}
internal static bool CanClaim(string id)
{
return (Object)(object)ClaimTarget(id) != (Object)null;
}
internal static string[] Choices()
{
HashSet<string> upgrades = Upgrades();
List<string> list = AddressablesManager.Instance.GetAllRelics().Keys.Where((string id) => !upgrades.Contains(id) && Eligible(id) && !RelicManager.Instance.HasRelic(id)).ToList();
Random random = new Random();
for (int num = 0; num < Math.Min(3, list.Count); num++)
{
int index = random.Next(num, list.Count);
string value = list[index];
list[index] = list[num];
list[num] = value;
}
return list.Take(3).ToArray();
}
internal static bool CollectRelic(Contract contract, string id, Relic target, Action<Exception> warn)
{
if ((Object)(object)target == (Object)null || (Object)(object)ClaimTarget(id) != (Object)(object)target)
{
return false;
}
RelicManager manager = RelicManager.Instance;
string targetId = ((Item)target).GetIdentifier();
return contract.Collect(id, ((Object)target).name, delegate
{
manager.AddRelic(id);
}, () => manager.HasRelic(targetId), warn);
}
internal static bool CollectCoins(Contract contract, Action<Exception> warn)
{
ResourceManager instance = ResourceManager.Instance;
if (!contract.CollectCoins((Func<int>)instance.GetCoins, (Action<int>)instance.AddToCoins, warn))
{
return false;
}
try
{
StatisticsManager.Instance.AddCoins(contract.Terms.Coins);
}
catch (Exception obj)
{
warn(obj);
}
try
{
instance.ResourceAmountChanged((ResourceType)12);
}
catch (Exception obj2)
{
warn(obj2);
}
return true;
}
}
internal enum OrderKind
{
Bread,
Timber,
Stone,
Boards,
Grain,
Fish,
Water
}
internal sealed class OrderTerms
{
internal readonly OrderKind Kind;
internal readonly string Title;
internal readonly ResourceType Slot;
internal readonly int Quantity;
internal readonly int Coins;
private static readonly OrderTerms[] Catalog = new OrderTerms[7]
{
new OrderTerms(OrderKind.Bread, "Bread for the Watch", (ResourceType)9, 6, 0),
new OrderTerms(OrderKind.Timber, "Firewood for Camp", (ResourceType)2, 3, 2),
new OrderTerms(OrderKind.Stone, "Mend the Wall", (ResourceType)4, 4, 3),
new OrderTerms(OrderKind.Boards, "Repair the Bridge", (ResourceType)3, 5, 5),
new OrderTerms(OrderKind.Grain, "Stock the Granary", (ResourceType)7, 4, 3),
new OrderTerms(OrderKind.Fish, "Feed the Scouts", (ResourceType)11, 3, 2),
new OrderTerms(OrderKind.Water, "Fill the Canteens", (ResourceType)1, 2, 1)
};
internal string Reward
{
get
{
if (Coins != 0)
{
if (Coins != 1)
{
return $"{Coins} coins";
}
return "1 coin";
}
return "Choose 1 of 3 run relics";
}
}
internal string Difficulty
{
get
{
if (Quantity > 3)
{
if (Quantity != 4)
{
return "Hard";
}
return "Standard";
}
return "Easy";
}
}
private OrderTerms(OrderKind kind, string title, ResourceType slot, int quantity, int coins)
{
//IL_0015: Unknown result type (might be due to invalid IL or missing references)
//IL_0016: Unknown result type (might be due to invalid IL or missing references)
Kind = kind;
Title = title;
Slot = slot;
Quantity = quantity;
Coins = coins;
}
internal static OrderTerms Get(OrderKind kind)
{
return Catalog[(int)kind];
}
}
[BepInPlugin("sfk.weeklycontracts", "Weekly Contracts", "0.1.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class Plugin : BaseUnityPlugin
{
[HarmonyPatch(typeof(UICalendar), "OnEnable")]
private static class CalendarLink
{
[Serializable]
[CompilerGenerated]
private sealed class <>c
{
public static readonly <>c <>9 = new <>c();
public static UnityAction <>9__0_0;
internal void <Postfix>b__0_0()
{
if (Accessible && OverlayManager.Instance.IsCalendarOpen())
{
OverlayManager.Instance.CloseOverlay(false);
Instance.Show();
}
}
}
private static void Postfix(UICalendar __instance, TextMeshProUGUI ___textCycle, GameObject ___firstDay)
{
//IL_021e: Unknown result type (might be due to invalid IL or missing references)
//IL_0228: Expected O, but got Unknown
//IL_0096: Unknown result type (might be due to invalid IL or missing references)
//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
//IL_00a6: Expected O, but got Unknown
//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
//IL_00de: Expected O, but got Unknown
//IL_0109: Unknown result type (might be due to invalid IL or missing references)
//IL_0110: Unknown result type (might be due to invalid IL or missing references)
//IL_0112: Unknown result type (might be due to invalid IL or missing references)
//IL_0113: Unknown result type (might be due to invalid IL or missing references)
//IL_011a: Unknown result type (might be due to invalid IL or missing references)
//IL_012c: Unknown result type (might be due to invalid IL or missing references)
//IL_0242: Unknown result type (might be due to invalid IL or missing references)
//IL_0247: Unknown result type (might be due to invalid IL or missing references)
//IL_024d: Expected O, but got Unknown
//IL_0266: Unknown result type (might be due to invalid IL or missing references)
//IL_026b: Unknown result type (might be due to invalid IL or missing references)
//IL_0147: Unknown result type (might be due to invalid IL or missing references)
//IL_014e: Expected O, but got Unknown
//IL_036c: Unknown result type (might be due to invalid IL or missing references)
//IL_0374: Unknown result type (might be due to invalid IL or missing references)
//IL_0379: Unknown result type (might be due to invalid IL or missing references)
//IL_037d: Unknown result type (might be due to invalid IL or missing references)
//IL_0383: Invalid comparison between Unknown and I4
//IL_0193: Unknown result type (might be due to invalid IL or missing references)
//IL_0198: Unknown result type (might be due to invalid IL or missing references)
//IL_01b1: Unknown result type (might be due to invalid IL or missing references)
//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
//IL_02bb: Unknown result type (might be due to invalid IL or missing references)
//IL_02c1: Invalid comparison between Unknown and I4
//IL_03bd: Unknown result type (might be due to invalid IL or missing references)
//IL_032b: Unknown result type (might be due to invalid IL or missing references)
Transform obj = ((Component)__instance).transform.Find("Contract row");
RectTransform val = (RectTransform)(object)((obj is RectTransform) ? obj : null);
Transform obj2 = ((Component)__instance).transform.Find("Weekly contract");
Button val2 = ((obj2 != null) ? ((Component)obj2).GetComponent<Button>() : null);
if (!Accessible)
{
if ((Object)(object)val != (Object)null)
{
((Component)val).gameObject.SetActive(false);
}
if ((Object)(object)val2 != (Object)null)
{
((Component)val2).gameObject.SetActive(false);
}
return;
}
if ((Object)(object)val == (Object)null)
{
val = (RectTransform)new GameObject("Contract row", new Type[2]
{
typeof(RectTransform),
typeof(LayoutElement)
}).transform;
((Transform)val).SetParent(((Component)__instance).transform, false);
RectTransform val3 = (RectTransform)Object.Instantiate<Transform>(Resources.Load<GameObject>("UI/OverlayMessage").transform.Find("Buttons/BuyButton"), ((Component)__instance).transform, false);
((Object)val3).name = "Weekly contract";
((Component)val3).GetComponent<LayoutElement>().ignoreLayout = true;
Vector2 val4 = default(Vector2);
((Vector2)(ref val4))..ctor(0.5f, 0f);
val3.pivot = val4;
Vector2 anchorMin = (val3.anchorMax = val4);
val3.anchorMin = anchorMin;
val3.anchoredPosition = new Vector2(0f, 8f);
foreach (Transform item in (Transform)val3)
{
Transform val6 = item;
((Component)val6).gameObject.SetActive(((Object)val6).name == "Text");
}
val2 = ((Component)val3).GetComponent<Button>();
Rect rect = val3.rect;
float num = ((Rect)(ref rect)).height + 16f;
val.sizeDelta = new Vector2(1f, num);
((Component)val).GetComponent<LayoutElement>().preferredHeight = num;
}
((Component)val).gameObject.SetActive(true);
((Component)val2).gameObject.SetActive(true);
TextMeshProUGUI component = ((Component)((Component)val2).transform.Find("Text")).GetComponent<TextMeshProUGUI>();
((Behaviour)((Component)component).GetComponent<LocalizeStringEvent>()).enabled = false;
((TMP_Text)component).text = ((TMP_Text)___textCycle).text + " - Contract";
((Selectable)val2).interactable = true;
val2.onClick = new ButtonClickedEvent();
ButtonClickedEvent onClick = val2.onClick;
object obj3 = <>c.<>9__0_0;
if (obj3 == null)
{
UnityAction val7 = delegate
{
if (Accessible && OverlayManager.Instance.IsCalendarOpen())
{
OverlayManager.Instance.CloseOverlay(false);
Instance.Show();
}
};
<>c.<>9__0_0 = val7;
obj3 = (object)val7;
}
((UnityEvent)onClick).AddListener((UnityAction)obj3);
Selectable component2 = ___firstDay.GetComponent<Selectable>();
if ((Object)(object)component2 != (Object)null)
{
Navigation navigation = ((Selectable)val2).navigation;
((Navigation)(ref navigation)).mode = (Mode)4;
((Navigation)(ref navigation)).selectOnDown = component2;
Transform parent = ___firstDay.transform.parent;
for (int num2 = 21; num2 < Math.Min(28, parent.childCount); num2++)
{
Selectable component3 = ((Component)parent.GetChild(num2)).GetComponent<Selectable>();
if ((Object)(object)component3 == (Object)null)
{
continue;
}
Navigation navigation2 = component3.navigation;
if ((int)((Navigation)(ref navigation2)).mode != 4)
{
((Navigation)(ref navigation2)).selectOnLeft = component3.FindSelectableOnLeft();
((Navigation)(ref navigation2)).selectOnRight = component3.FindSelectableOnRight();
((Navigation)(ref navigation2)).selectOnUp = component3.FindSelectableOnUp();
((Navigation)(ref navigation2)).selectOnDown = component3.FindSelectableOnDown();
}
if (!((Object)(object)((Navigation)(ref navigation2)).selectOnDown != (Object)null) || !((Object)(object)((Navigation)(ref navigation2)).selectOnDown != (Object)(object)val2))
{
((Navigation)(ref navigation2)).mode = (Mode)4;
((Navigation)(ref navigation2)).selectOnDown = (Selectable)(object)val2;
component3.navigation = navigation2;
if ((Object)(object)((Navigation)(ref navigation)).selectOnUp == (Object)null || num2 == 24)
{
((Navigation)(ref navigation)).selectOnUp = component3;
}
}
}
((Selectable)val2).navigation = navigation;
Navigation navigation3 = component2.navigation;
if ((int)((Navigation)(ref navigation3)).mode != 4)
{
((Navigation)(ref navigation3)).selectOnRight = component2.FindSelectableOnRight();
((Navigation)(ref navigation3)).selectOnDown = component2.FindSelectableOnDown();
((Navigation)(ref navigation3)).selectOnLeft = component2.FindSelectableOnLeft();
}
((Navigation)(ref navigation3)).mode = (Mode)4;
((Navigation)(ref navigation3)).selectOnUp = (Selectable)(object)val2;
component2.navigation = navigation3;
}
GamepadManager.Instance.SetGameObjectToSelect(((Component)val2).gameObject, true);
if ((Object)(object)EventSystem.current != (Object)null)
{
EventSystem.current.SetSelectedGameObject(((Component)val2).gameObject);
}
}
}
internal static Contract Current;
internal static Contract Restored;
internal static Plugin Instance;
private Harmony harmony;
private UIOverlayMessage card;
private bool announce;
private float worldReadySince = -1f;
private int index;
private bool waitForRelease;
internal static bool Accessible
{
get
{
if (Current != null)
{
if (Current.stage != Stage.Offered && Current.stage != Stage.Active)
{
return Current.stage == Stage.Earned;
}
return true;
}
return false;
}
}
private void Awake()
{
//IL_004c: Unknown result type (might be due to invalid IL or missing references)
//IL_0056: Expected O, but got Unknown
Instance = this;
Chainloader.PluginInfos.TryGetValue("ownly.morerelics", out var value);
RewardPolicy.Bind((value == null) ? null : ((object)value.Instance)?.GetType().Assembly, delegate(string message)
{
((BaseUnityPlugin)this).Logger.LogWarning((object)message);
});
harmony = new Harmony("sfk.weeklycontracts");
harmony.PatchAll(typeof(SaveHooks.Read));
harmony.PatchAll(typeof(SaveHooks.Raw));
harmony.PatchAll(typeof(SaveHooks.Tavern));
harmony.PatchAll(typeof(SaveHooks.TavernData));
harmony.PatchAll(typeof(SaveHooks.Save));
harmony.PatchAll(typeof(CalendarLink));
GameManager.OnGameInit += ResetRun;
DaytimeManager.OnMorningStart += Dawn;
DaytimeManager.OnDayStart += Day;
DaytimeManager.OnNightStart += Night;
((BaseUnityPlugin)this).Logger.LogInfo((object)"Weekly Contracts ready.");
}
private void OnDestroy()
{
GameManager.OnGameInit -= ResetRun;
DaytimeManager.OnMorningStart -= Dawn;
DaytimeManager.OnDayStart -= Day;
DaytimeManager.OnNightStart -= Night;
Harmony obj = harmony;
if (obj != null)
{
obj.UnpatchSelf();
}
ResetRun();
Instance = null;
}
private void ResetRun()
{
Current = null;
Restored = null;
card = null;
announce = false;
worldReadySince = -1f;
}
private void Dawn(int day)
{
string runID = GameDataManager.Instance.GetRunID();
if (string.IsNullOrEmpty(runID))
{
return;
}
if (Current == null || Current.run != runID)
{
Current = ((Restored != null && Restored.run == runID) ? Restored : new Contract
{
run = runID
});
}
Restored = null;
if (Current.AtDawn(day))
{
announce = true;
worldReadySince = -1f;
}
if (Current.stage == Stage.Offered && (Current.offers == null || Current.offers.Length == 0))
{
Current.offers = Kingdom.Offers(day);
if (Current.offers.Length == 0)
{
Current.stage = Stage.Expired;
announce = false;
}
}
}
private static void Day(int day)
{
Current?.Advance(day, morning: false, night: false);
}
private static void Night(int day)
{
Current?.Advance(day, morning: false, night: true);
}
private void Update()
{
if (waitForRelease && !SubmitHeld())
{
waitForRelease = false;
}
if (!announce || Current == null)
{
return;
}
if (Current.stage != Stage.Offered)
{
announce = false;
return;
}
if ((Object)(object)GameManager.Instance == (Object)null || !GameManager.Instance.IsGameRunning() || (Object)(object)UIManager.Instance == (Object)null || !UIManager.Instance.IsWorldInteractable() || (Object)(object)DaytimeManager.Instance == (Object)null || !DaytimeManager.Instance.IsMorning() || ((Object)(object)DialogueManager.Instance != (Object)null && DialogueManager.Instance.IsInDialogue()))
{
worldReadySince = -1f;
return;
}
if (worldReadySince < 0f)
{
worldReadySince = Time.unscaledTime;
}
if (!(Time.unscaledTime - worldReadySince < 0.5f))
{
announce = false;
Show();
}
}
private void Refresh()
{
DaytimeManager instance = DaytimeManager.Instance;
if (Current != null && (Object)(object)instance != (Object)null)
{
Current.Advance(instance.CurrentDay(), instance.IsMorning(), instance.IsNight());
}
}
private void Close()
{
card = null;
OverlayManager.Instance.CloseOverlay(false);
}
private void Show()
{
//IL_0048: Unknown result type (might be due to invalid IL or missing references)
//IL_004d: Unknown result type (might be due to invalid IL or missing references)
announce = false;
Refresh();
OrderTerms order = Current.Terms;
ResourceData val = Kingdom.Material(Current.selected);
string arg = (Kingdom.Supported(val) ? val.GetName() : ((object)order.Slot/*cast due to .constrained prefix*/).ToString());
switch (Current.stage)
{
case Stage.Offered:
Page(Current.OfferMessage, "Later", Close, "Decline…", Decline, allowLater: false, Current.offers, "Weekly Contracts");
break;
case Stage.Active:
{
int num = Kingdom.Stock(val);
Page($"{num} unreserved {arg} available.", (num >= order.Quantity) ? $"Deliver {order.Quantity}…" : null, ReviewDelivery, "Back", Close, allowLater: false, null, "Accepted Contract", Current.selected);
break;
}
case Stage.Earned:
Page("Delivery complete. Your reward is ready.", "Collect Reward", delegate
{
if (order.Coins > 0)
{
if (Kingdom.CollectCoins(Current, WarnReward))
{
Close();
}
else
{
RetryReward();
}
}
else
{
index = 0;
Reward();
}
}, "Later", Close, allowLater: false, null, "Contract Reward", Current.selected);
break;
default:
Page((Current.stage == Stage.Claimed) ? "Relic already collected." : "This contract is closed.", null, null, "Back", Close);
break;
}
}
private void ReviewOffer(OrderKind kind)
{
//IL_0049: Unknown result type (might be due to invalid IL or missing references)
//IL_004e: Unknown result type (might be due to invalid IL or missing references)
if (Current.stage != Stage.Offered)
{
Show();
return;
}
OrderTerms orderTerms = OrderTerms.Get(kind);
ResourceData val = Kingdom.Material(kind);
string arg = (Kingdom.Supported(val) ? val.GetName() : ((object)orderTerms.Slot/*cast due to .constrained prefix*/).ToString());
Page($"{Kingdom.Stock(val)} {arg} available. Accepting costs nothing.", "Accept", delegate
{
if (Current.Accept(kind))
{
Close();
}
else
{
Show();
}
}, "Back", Show, allowLater: false, null, "Contract Terms", kind);
}
private void Decline()
{
Page("Decline all contracts for this week? Your stock stays the same.", "Decline", delegate
{
Current.Decide(accept: false);
Close();
}, "Keep Offer", Show);
}
private void ReviewDelivery()
{
//IL_006e: Unknown result type (might be due to invalid IL or missing references)
//IL_0073: Unknown result type (might be due to invalid IL or missing references)
ResourceData val = Kingdom.Material(Current.selected);
OrderTerms order = Current.Terms;
int cost = order.Quantity;
int before = Kingdom.Stock(val);
if (Current.stage != Stage.Active || before < cost)
{
Show();
return;
}
ResourceType type = val.type;
Page($"Commit {cost} {val.GetName()}? Your available stock will go from {before} to {before - cost}.", "Confirm", delegate
{
//IL_0026: Unknown result type (might be due to invalid IL or missing references)
//IL_002c: Unknown result type (might be due to invalid IL or missing references)
ResourceData val2 = Kingdom.Material(Current.selected);
if (Current.stage != Stage.Active || !Kingdom.Supported(val2) || val2.type != type || Kingdom.Stock(val2) != before)
{
Show();
}
else if (Kingdom.Deliver(Current, val2))
{
Show();
}
else
{
Page($"Delivery unavailable. You need {cost} spendable {val2.GetName()}" + ((order.Coins == 0) ? " and three eligible relics." : "."), null, null, "Back", Show);
}
}, "Back", Show, allowLater: false, null, "Confirm Delivery", Current.selected);
}
private void Reward()
{
if (Current.stage != Stage.Earned)
{
Show();
return;
}
if (Current.rewards == null || !Current.rewards.Any(Kingdom.CanClaim))
{
ResourceData val = Kingdom.PaidFood(Current);
string text = (((Object)(object)val != (Object)null) ? ("Take your six " + val.GetName() + " back or keep the reward for later.") : "Restore the paid resource definition to collect a refund, or keep the reward for later.");
Page("Your relics are currently unavailable. " + text, ((Object)(object)val != (Object)null) ? "Refund" : null, delegate
{
if (Kingdom.ReturnPayment(Current))
{
Close();
}
else
{
Show();
}
}, "Later", Close);
return;
}
string id = Current.rewards[index];
Relic target = Kingdom.ClaimTarget(id);
bool flag = (Object)(object)target != (Object)null;
Relic val2 = ((flag || string.IsNullOrEmpty(id)) ? target : AddressablesManager.Instance.GetRelic(id));
string title = (((Object)(object)val2 != (Object)null) ? ((Item)val2).GetTitle() : id);
string detail = (flag ? ((Item)val2).GetDescription() : "Currently unavailable.");
string message = $"Relic {index + 1} of 3 • {title}\n{detail}";
string primary = (flag ? "Choose…" : null);
Action accept = delegate
{
ConfirmReward(id, target, title, detail);
};
Action other = delegate
{
index = (index + 1) % Current.rewards.Length;
Reward();
};
Sprite art = (((Object)(object)val2 != (Object)null) ? ((Item)val2).GetIcon() : null);
Page(message, primary, accept, "Next Relic", other, allowLater: true, null, "Choose Your Relic", null, art);
}
private void ConfirmReward(string id, Relic target, string title, string description)
{
string message = "Collect " + title + " as your contract reward?";
Action accept = delegate
{
if ((Object)(object)target != (Object)null && (Object)(object)Kingdom.ClaimTarget(id) == (Object)(object)target && ((Item)target).GetTitle() == title && ((Item)target).GetDescription() == description)
{
if (Kingdom.CollectRelic(Current, id, target, WarnReward))
{
Close();
}
else
{
RetryReward();
}
}
else
{
Reward();
}
};
Action other = Reward;
Sprite icon = ((Item)target).GetIcon();
Page(message, "Collect", accept, "Back", other, allowLater: false, null, "Collect Relic", null, icon);
}
private void WarnReward(Exception error)
{
((BaseUnityPlugin)this).Logger.LogWarning((object)("Contract reward provider: " + error.GetBaseException().Message));
}
private void RetryReward()
{
Page("Your reward was not received. You can collect it again.", "Back", Show, "Later", Close);
}
private static bool SubmitHeld()
{
EventSystem current = EventSystem.current;
BaseInputModule obj = ((current != null) ? current.currentInputModule : null);
InputSystemUIInputModule val = (InputSystemUIInputModule)(object)((obj is InputSystemUIInputModule) ? obj : null);
if ((Object)(object)val != (Object)null && (Object)(object)val.submit != (Object)null)
{
return val.submit.action.IsPressed();
}
return false;
}
private void Page(string message, string primary, Action accept, string secondary, Action other, bool allowLater = false, OrderKind[] rows = null, string heading = null, OrderKind? summary = null, Sprite art = null)
{
//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
//IL_0100: Expected O, but got Unknown
//IL_0101: Unknown result type (might be due to invalid IL or missing references)
//IL_010b: Expected O, but got Unknown
//IL_011c: Unknown result type (might be due to invalid IL or missing references)
//IL_0126: Expected O, but got Unknown
//IL_0142: Unknown result type (might be due to invalid IL or missing references)
//IL_014c: Expected O, but got Unknown
//IL_019b: Unknown result type (might be due to invalid IL or missing references)
//IL_01a5: Expected O, but got Unknown
//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
//IL_01bd: Expected O, but got Unknown
//IL_0271: Unknown result type (might be due to invalid IL or missing references)
//IL_027b: Expected O, but got Unknown
if ((Object)(object)card != (Object)null && ((Component)card).gameObject.activeInHierarchy)
{
((Component)card).gameObject.SetActive(false);
}
UIOverlayMessage next = OverlayManager.Instance.OverlayMessage(true);
card = next;
int opened = Time.frameCount;
Contract origin = Current;
waitForRelease = SubmitHeld();
next.SetMessage(message);
if (heading != null)
{
ContractCards.Heading(next, heading);
}
if ((Object)(object)art != (Object)null)
{
ContractCards.RelicArt(next, art);
}
Button component = ((Component)((Component)next).transform.Find("Buttons/BuyButton")).GetComponent<Button>();
Button component2 = ((Component)((Component)next).transform.Find("Buttons/Cancel")).GetComponent<Button>();
component.onClick = new ButtonClickedEvent();
component2.onClick = new ButtonClickedEvent();
if (primary != null)
{
next.SetAccept(primary, (UnityAction)delegate
{
Invoke(accept);
});
}
else
{
next.RemoveAccept();
}
next.SetCancel(secondary, (UnityAction)delegate
{
Invoke(other);
});
if (allowLater)
{
VerticalLayoutGroup component3 = ((Component)next).GetComponent<VerticalLayoutGroup>();
((LayoutGroup)component3).padding.bottom = ((LayoutGroup)component3).padding.top;
Button val = Object.Instantiate<Button>(component2, ((Component)next).transform);
((TMP_Text)((Component)val).GetComponentInChildren<TextMeshProUGUI>()).text = "Later";
val.onClick = new ButtonClickedEvent();
((UnityEvent)val.onClick).AddListener((UnityAction)delegate
{
Invoke(Close);
});
LinkButtons((primary != null) ? component : null, component2, val);
}
Button val2 = ((primary != null) ? component : component2);
if (summary.HasValue)
{
ContractCards.Order(next, component, summary.Value, Current.deadline, selectable: false);
}
if (rows != null && rows.Length != 0)
{
Button[] array = (Button[])(object)new Button[rows.Length];
for (int num = 0; num < rows.Length; num++)
{
OrderKind kind = rows[num];
((UnityEvent)(array[num] = ContractCards.Order(next, component, kind, Current.deadline, selectable: true)).onClick).AddListener((UnityAction)delegate
{
Invoke(delegate
{
ReviewOffer(kind);
});
});
}
for (int num2 = 0; num2 < array.Length; num2++)
{
Navigate(array[num2], (num2 == 0) ? component : array[num2 - 1], (num2 + 1 == array.Length) ? component : array[num2 + 1], null);
}
Navigate(component, array[^1], array[0], component2);
Navigate(component2, array[^1], array[0], component);
val2 = array[0];
}
GamepadManager.Instance.SetGameObjectToSelect(((Component)val2).gameObject, true);
if ((Object)(object)EventSystem.current != (Object)null)
{
EventSystem.current.SetSelectedGameObject(((Component)val2).gameObject);
}
void Invoke(Action action)
{
if (!((Object)(object)card != (Object)(object)next) && ((Component)next).gameObject.activeInHierarchy && Current == origin && Time.frameCount != opened && !waitForRelease && !GameManager.Instance.IsUnloading())
{
Refresh();
action();
}
}
}
private static void Navigate(Button button, Button up, Button down, Button side)
{
//IL_0003: Unknown result type (might be due to invalid IL or missing references)
//IL_0031: Unknown result type (might be due to invalid IL or missing references)
Navigation navigation = default(Navigation);
((Navigation)(ref navigation)).mode = (Mode)4;
((Navigation)(ref navigation)).selectOnUp = (Selectable)(object)up;
((Navigation)(ref navigation)).selectOnDown = (Selectable)(object)down;
((Navigation)(ref navigation)).selectOnLeft = (Selectable)(object)side;
((Navigation)(ref navigation)).selectOnRight = (Selectable)(object)side;
((Selectable)button).navigation = navigation;
}
private static void LinkButtons(Button primary, Button secondary, Button later)
{
//IL_0025: Unknown result type (might be due to invalid IL or missing references)
//IL_002a: Unknown result type (might be due to invalid IL or missing references)
//IL_007d: Unknown result type (might be due to invalid IL or missing references)
Button[] array = (Button[])(object)new Button[3] { primary, secondary, later };
foreach (Button val in array)
{
if (!((Object)(object)val == (Object)null))
{
Navigation navigation = ((Selectable)val).navigation;
((Navigation)(ref navigation)).mode = (Mode)4;
Button val2 = (((Object)(object)val == (Object)(object)primary) ? secondary : primary);
Selectable selectOnLeft = (((Navigation)(ref navigation)).selectOnRight = (Selectable)(object)val2);
((Navigation)(ref navigation)).selectOnLeft = selectOnLeft;
selectOnLeft = (((Navigation)(ref navigation)).selectOnUp = (Selectable)(object)(((Object)(object)val == (Object)(object)later) ? (primary ?? secondary) : later));
((Navigation)(ref navigation)).selectOnDown = selectOnLeft;
((Selectable)val).navigation = navigation;
}
}
}
}
internal static class RewardPolicy
{
private static readonly Dictionary<string, Func<bool>> rules = new Dictionary<string, Func<bool>>();
internal static void Bind(Assembly assembly, Action<string> warn)
{
rules.Clear();
if (assembly == null)
{
return;
}
try
{
foreach (object entry in (assembly.GetType("MoreRelics.Registry", throwOnError: true).GetField("Entries", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null) as IEnumerable) ?? throw new MissingFieldException("Registry.Entries"))
{
Type type = entry.GetType();
PropertyInfo definition = type.GetProperty("Def");
object obj = definition?.GetValue(entry);
string id = obj?.GetType().GetField("id")?.GetValue(obj) as string;
FieldInfo bossOnly = obj?.GetType().GetField("bossOnly");
PropertyInfo available = type.GetProperty("Available");
if (string.IsNullOrEmpty(id) || bossOnly?.FieldType != typeof(bool) || available?.PropertyType != typeof(bool))
{
throw new MissingMemberException(type.FullName);
}
bool reported = false;
rules[id] = delegate
{
try
{
return !(bool)bossOnly.GetValue(definition.GetValue(entry)) && (bool)available.GetValue(entry);
}
catch (Exception ex2)
{
if (!reported)
{
warn("Cannot check " + id + ". Skipping this reward. " + ex2.GetBaseException().Message);
}
reported = true;
return false;
}
};
}
}
catch (Exception ex)
{
rules.Clear();
warn("MoreRelics metadata unavailable. Using native reward rules. " + ex.Message);
}
}
internal static bool Allows(string id)
{
if (rules.TryGetValue(id, out var value))
{
return value();
}
return true;
}
}
internal static class SaveHooks
{
[Serializable]
private sealed class Envelope
{
public string runID;
public string hash;
public int coins;
public string[] relics;
public Contract sfkWeeklyContracts;
}
[HarmonyPatch(typeof(GameDataManager), "PositionWorldBuildings")]
internal static class Read
{
private static void Prefix()
{
BeginRead();
}
private static void Postfix(GameData ___m_GameData)
{
Restore(___m_GameData);
}
private static void Finalizer()
{
EndRead();
}
}
[HarmonyPatch(typeof(TavernSaveManager), "Load")]
internal static class Tavern
{
private static void Prefix()
{
BeginRead();
}
private static void Finalizer()
{
EndRead();
}
}
[HarmonyPatch(typeof(SaveManager), "LoadGameData")]
internal static class TavernData
{
private static void Postfix(GameData __result)
{
if (reading)
{
Restore(__result);
}
}
}
[HarmonyPatch]
internal static class Raw
{
private static MethodBase TargetMethod()
{
return AccessTools.FirstMethod(typeof(SaveManager), (Func<MethodInfo, bool>)((MethodInfo m) => m.Name == "Load" && !m.IsGenericMethod && m.ReturnType == typeof(string)));
}
private static void Postfix(string __0, string __result)
{
Observe(__0, __result);
}
}
[HarmonyPatch(typeof(SaveManager), "Save", new Type[]
{
typeof(string),
typeof(string)
})]
internal static class Save
{
internal static void Prefix(string __0, ref string __1)
{
Contract contract = Plugin.Current ?? Plugin.Restored;
if (contract == null || __0 == null || !__0.EndsWith("_game", StringComparison.Ordinal) || string.IsNullOrEmpty(__1))
{
return;
}
int num = __1.LastIndexOf('}');
if (num >= 0)
{
Envelope envelope = JsonUtility.FromJson<Envelope>(__1);
if (!(envelope.runID != contract.run))
{
contract = contract.ForCheckpoint(envelope.coins, envelope.relics);
__1 = __1.Insert(num, ",\"sfkWeeklyContracts\":" + JsonUtility.ToJson((object)contract));
}
}
}
}
private static Envelope selected;
private static bool reading;
internal static void BeginRead()
{
selected = null;
Plugin.Current = (Plugin.Restored = null);
reading = true;
}
internal static void Observe(string path, string json)
{
if (!reading || path == null || !path.EndsWith("_game", StringComparison.Ordinal))
{
return;
}
selected = null;
if (string.IsNullOrEmpty(json) || !json.Contains("\"sfkWeeklyContracts\""))
{
return;
}
try
{
selected = JsonConvert.DeserializeObject<Envelope>(json);
}
catch (JsonException)
{
}
}
internal static void Restore(GameData game)
{
Envelope envelope = selected;
if (game != null && envelope != null && envelope.runID == game.runID && envelope.hash == game.hash && envelope.sfkWeeklyContracts?.run == game.runID)
{
Plugin.Restored = envelope.sfkWeeklyContracts;
}
}
internal static void EndRead()
{
reading = false;
selected = null;
}
}