using System;
using NCMS;
using System.Net;
using System.IO;
using System.Text;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ReflectionUtility;

namespace Diplomacy_Army
{
	[ModEntry]
	public class NewFunction
	{
		private static string path = ".\\players.json";
		public static Color color1 = new Color(1f, 0.1f, 0.1f, 0.2f);

		private static int chance = 0;
		private static int _opinion_close_borders = 0;
		private static int _opinion_same_wars = 0;
		private static int _opinion_total = 0;
		private static int _opinion_total_2 = 0;

		private static DiplomacyRelation relation;
		private static KingdomOpinion kingdomOpinion;
		private static KingdomOpinion kingdomOpinion2;
		private static ActorStatus actorStatus;
		private static ActorStatus actorStatus2;

		private static Treaty newTreaty;
		private static string message;
		private static string message2;

		public static void AddNewText(string message, Color color, Sprite icon = null)
		{
            GameObject gameObject = HistoryHud.instance.GetObject();
            gameObject.name = "HistoryItem " + (object)(HistoryHud.historyItems.Count + 1);
            gameObject.SetActive(true);

            gameObject.transform.Find("CText").GetComponent<Text>();
            gameObject.transform.SetParent(HistoryHud.contentGroup);
            RectTransform component = gameObject.GetComponent<RectTransform>();
            component.localScale = Vector3.one;
            component.localPosition = Vector3.zero;
            component.SetLeft(0.0f);

            float top = (float)HistoryHud.instance.CallMethod("recalcPositions");

            component.SetTop(top);
            component.sizeDelta = new Vector2(component.sizeDelta.x, 15f);
            gameObject.GetComponent<HistoryHudItem>().targetBottom = top;

            gameObject.GetComponent<HistoryHudItem>().textField.color = color;
            gameObject.GetComponent<HistoryHudItem>().textField.text = message;
            HistoryHud.historyItems.Add(gameObject.GetComponent<HistoryHudItem>());
            Reflection.SetField<bool>(HistoryHud.instance, "recalc", true);

            if(icon != null)
            {
                gameObject.transform.Find("Icon").GetComponent<Image>().sprite = icon;
            }

            gameObject.SetActive(true);
        }

		public static void LogNewMessage(Kingdom pKingdom, string pMessage = "")
		{
			if (pKingdom == null)
			{
				return;
			}
			pMessage = ">>:" + pMessage;
			if (Main.KingdomMessages.ContainsKey(pKingdom))
			{
				if (!Main.KingdomMessages[pKingdom].ContainsKey(pMessage))
				{
					Main.KingdomMessages[pKingdom].Add(pMessage, DateTime.Now.ToLocalTime().AddSeconds(3.0f));
				}
				else
				{
					Main.KingdomMessages[pKingdom][pMessage] = DateTime.Now.ToLocalTime().AddSeconds(3.0f);
				}
			}
			else
			{
				Dictionary<string, DateTime> notice = new Dictionary<string, DateTime>() { { pMessage, DateTime.Now.ToLocalTime().AddSeconds(3.0f) } };
				Main.KingdomMessages.Add(pKingdom, notice);
			}
		}

		public static GameObject CreateNewButton(int index, Transform pParent, string pSprite, GodPower pID, string pDescription, UnityAction pCall = null, PowerButtonType type = PowerButtonType.Active)
		{
			((Dictionary<string,string>)Reflection.GetField(LocalizedTextManager.instance.GetType(),LocalizedTextManager.instance,"localizedText")).Add(pID.name,pID.name);
			((Dictionary<string,string>)Reflection.GetField(LocalizedTextManager.instance.GetType(),LocalizedTextManager.instance,"localizedText")).Add(pID.name + " Description",pDescription);
			float x = 520f + (float)(36 * (index / 2));
			float y = 18f - (float)(36 * (index % 2));
			Sprite sprite = null;
			foreach (GameObject gameObject in Resources.FindObjectsOfTypeAll<GameObject>())
			{
				if (gameObject.transform.name == pSprite)
				{
					sprite = gameObject.transform.Find("Icon").GetComponent<Image>().sprite;
				}
			}
			GameObject gameObject2 = UnityEngine.Object.Instantiate<GameObject>(GameObject.Find("SettingsButton"), pParent);
			gameObject2.GetComponent<PowerButton>().type = type;
			Reflection.SetField<GodPower>(gameObject2.GetComponent<PowerButton>(), "godPower", pID);
			gameObject2.GetComponent<PowerButton>().custom_tooltip_name = pID.name;
			gameObject2.GetComponent<PowerButton>().custom_tooltip_description = pDescription;
			gameObject2.transform.name = pID.id;
			gameObject2.transform.localScale = new Vector2(1f, 1f);
			gameObject2.transform.localPosition = new Vector2(x, y);
			gameObject2.transform.Find("Icon").GetComponent<Image>().sprite = sprite;
			gameObject2.GetComponent<Button>().onClick = new Button.ButtonClickedEvent();
			if(pCall!=null)
            {
				gameObject2.GetComponent<Button>().onClick.AddListener(pCall);
			}
			gameObject2.SetActive(true);
			return gameObject2;
		}

		public static GameObject CreateNewButtonOnWindow(Vector2 pLocalPosition, Transform pParent, string pSprite, GodPower pID, string pDescription, UnityAction pCall = null, PowerButtonType type = PowerButtonType.Active)
		{

			((Dictionary<string, string>)Reflection.GetField(LocalizedTextManager.instance.GetType(), LocalizedTextManager.instance, "localizedText")).Add(pID.name, pID.name);
			((Dictionary<string, string>)Reflection.GetField(LocalizedTextManager.instance.GetType(), LocalizedTextManager.instance, "localizedText")).Add(pID.name + " Description", pDescription);
			Sprite sprite = null;
			foreach (GameObject gameObject in Resources.FindObjectsOfTypeAll<GameObject>())
			{
				if (gameObject.transform.name == pSprite)
				{
					sprite = gameObject.transform.Find("Icon").GetComponent<Image>().sprite;
				}
			}
			GameObject gameObject2 = UnityEngine.Object.Instantiate<GameObject>(GameObject.Find("SettingsButton"), pParent);
			gameObject2.GetComponent<PowerButton>().type = type;
			Reflection.SetField<GodPower>(gameObject2.GetComponent<PowerButton>(), "godPower", pID);
			gameObject2.GetComponent<PowerButton>().custom_tooltip_name = pID.name;
			gameObject2.GetComponent<PowerButton>().custom_tooltip_description = pDescription;
			gameObject2.transform.name = pID.id;
			gameObject2.transform.localScale = new Vector2(1f, 1f);
			gameObject2.transform.localPosition = pLocalPosition;
			gameObject2.transform.Find("Icon").GetComponent<Image>().sprite = sprite;
			gameObject2.GetComponent<Button>().onClick = new Button.ButtonClickedEvent();
			if (pCall != null)
			{
				gameObject2.GetComponent<Button>().onClick.AddListener(pCall);
			}
			gameObject2.SetActive(true);
			return gameObject2;
		}

		public static Vector2 getPositionByIndex(int index)
		{

			// Starting position by x
			float startX = 50;

			// Starting position by y
			float startY = -20;

			// Buttons size + gap between
			float sizeWithGap = 40;

			// Buttons per row
			int buttonsPerRow = 5;

			// Calculating points
			float positionX = startX + (index * sizeWithGap) - ((Mathf.Floor(index / buttonsPerRow) * sizeWithGap) * buttonsPerRow);
			float positionY = startY - (Mathf.Floor(index / buttonsPerRow) * sizeWithGap);

			return new Vector2(positionX, positionY);
		}

		public static JObject ReadHtml(string html)
		{
			HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(html);
			httpWebRequest.Method = "GET";
			httpWebRequest.ContentType = "application/json";
			HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
			StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);
			JObject jObject = (JObject)JToken.ReadFrom(new JsonTextReader(streamReader));
			httpWebResponse.Close();
			return jObject;
		}

		public static JObject ReadJson(string path)
		{
			if (!File.Exists(path))
			{
				return null;
			}
			StreamReader streamReader = new StreamReader(path);
			JObject result = (JObject)JToken.ReadFrom(new JsonTextReader(streamReader));
			streamReader.Close();
			return result;
		}

		public static void WriteToJson(string path, string name)
		{
			if (!File.Exists(path))
			{
				return;
			}
			JObject jobject = JObject.Parse(File.ReadAllText(path, Encoding.UTF8));
			JObject jobject2 = new JObject(new JProperty("name", name));
			jobject["gameCmdDataList"].Last.AddAfterSelf(jobject2);
			string contents = Convert.ToString(jobject);
			File.WriteAllText(path, contents);
		}

		public static void LogNewMessage(Kingdom pKingdom, string pMessage = "", string pMessage2 = "")
		{
			var kingdomColor = (KingdomColor)Reflection.GetField(pKingdom.GetType(), pKingdom, "kingdomColor");
			var Message = string.Concat(new string[]
			{
				pMessage,
				"  <color=",
				Toolbox.colorToHex(kingdomColor.colorBorderOut, true),
				">",
				pKingdom.name,
				"</color>  ",
				pMessage2
			});
			NewFunction.AddNewText(Message, Toolbox.color_log_neutral);
		}

		public static void LogNewMessage(Kingdom pKingdom, Kingdom pKingdom2, string pMessage = "", string pMessage2 = "", string pMessage3 = "")
		{
            var kingdomColor = (KingdomColor)Reflection.GetField(pKingdom.GetType(), pKingdom, "kingdomColor");
			var kingdomColor2 = (KingdomColor)Reflection.GetField(pKingdom2.GetType(), pKingdom2, "kingdomColor");
			var Message = string.Concat(new string[]
			{
				pMessage,
				"  <color=",
				Toolbox.colorToHex(kingdomColor.colorBorderOut, true),
				">",
				pKingdom.name,
				"</color>  ",
				pMessage2,
				"  <color=",
				Toolbox.colorToHex(kingdomColor2.colorBorderOut, true),
				">",
				pKingdom2.name,
				"</color>  ",
				pMessage3
			});
			NewFunction.AddNewText(Message, Toolbox.color_log_neutral);
		}

		public static Kingdom GetKingdomByID(string ID)
        {
			foreach(Kingdom kingdom in MapBox.instance.kingdoms.list_civs)
            {
                if (kingdom.id.Equals(ID))
                {
					return kingdom;
                }
            }
			return null;
        }

		public static int getLengthOfString(string ID)
        {
			int length = 0;
			foreach(char c in ID)
            {
				length += 4;
                if (c <= 'Z' && c >= 'A')
                {
					length--;
                    if (c == 'I')
                    {
						length--;
                    }
                }
                if ((c <= 'z' && c >= 'a')||(c <= '9' && c >= '0'))
                {
					length -= 2;
                    if (c == 'i' || c == 'l' || c == 't' || c == 'f')
                    {
						length--;
                    }
                }
                if (c == ' ')
                {
					length -= 3;
                }
            }
			return length;
        }

		public static void MoveArmy(UnitGroup pArmy, WorldTile pTile)
		{
			if (pTile == null || pArmy == null)
			{
				return;
			}
			Reflection.SetField<TileZone>(pArmy.city, "target_attack_zone", pTile.zone);
			var units = Reflection.GetField(pArmy.GetType(), pArmy, "units") as ActorContainer;
			if (units.Count < pArmy.city.getArmy() * 2 / 3)
			{
				foreach (Actor actor in pArmy.city.professionsDict[UnitProfession.Warrior])
				{
					if (!units.Contains(actor))
					{
						//units.Add(actor);
						pArmy.addUnit(actor);
					}
				}
			}
			if (units.Count > 0)
			{
				foreach (Actor actor in units.getSimpleList())
				{
					actor.cancelAllBeh(null);
					((AiSystemActor)Reflection.GetField(actor.GetType(), actor, "ai")).setJob("attacker");
					Reflection.SetField<WorldTile>(actor, "beh_tile_target", pTile);
					actor.goTo(pTile);
				}
			}
		}

		public static void tryNewTreaty(Kingdom pKingdom)
        {
			tryNewAllianceTreaty(pKingdom);
			tryNewArmyTreaty(pKingdom);
			tryNewDefenceTreaty(pKingdom);
        }

		public static void tryNewAllianceTreaty(Kingdom pKingdom)
		{
			if (pKingdom.civs_allies.Count > 0 && pKingdom.king != null)
			{
				actorStatus = Reflection.GetField(pKingdom.king.GetType(), pKingdom.king, "data") as ActorStatus;
				if (MoreGodPower.AllianceKingdoms.ContainsKey(pKingdom) && MoreGodPower.AllianceKingdoms[pKingdom].Count > (actorStatus.diplomacy + 9) / 10)
				{
					return;
                }
				foreach (Kingdom kingdom in pKingdom.civs_allies.Keys)
				{
					if (kingdom.king != null && !MoreGodPower.KingdomsOwnedByPlayer.Contains(kingdom))
					{
						actorStatus2 = Reflection.GetField(kingdom.king.GetType(), kingdom.king, "data") as ActorStatus;
						if (!MoreGodPower.AllianceKingdoms.ContainsKey(kingdom) || MoreGodPower.AllianceKingdoms[kingdom].Count < (actorStatus2.diplomacy + 9) / 10)
						{
							relation = MapBox.instance.kingdoms.diplomacyManager.getRelation(pKingdom, kingdom);
							relation.recalculate(pKingdom, kingdom);
							kingdomOpinion = MapBox.instance.kingdoms.diplomacyManager.getOpinion(pKingdom, kingdom);
							_opinion_close_borders = (int)Reflection.GetField(kingdomOpinion.GetType(), kingdomOpinion, "_opinion_close_borders");
							_opinion_same_wars = (int)Reflection.GetField(kingdomOpinion.GetType(), kingdomOpinion, "_opinion_same_wars");
							if (_opinion_close_borders < 0 || _opinion_same_wars > 0)
							{
								kingdomOpinion2 = MapBox.instance.kingdoms.diplomacyManager.getOpinion(kingdom, pKingdom);
								_opinion_total_2 = (int)Reflection.GetField(kingdomOpinion2.GetType(), kingdomOpinion2, "_opinion_total");
								chance = actorStatus.diplomacy * 50 / (actorStatus.diplomacy + actorStatus2.diplomacy);
								if (_opinion_total_2 < 0)
								{
									chance /= 2;
								}
								if (Toolbox.randomInt(1, 100) < chance)
								{
									signNewTreaty(MoreGodPower.AllianceKingdoms, pKingdom, kingdom, "互不侵犯", 30, TreatyType.Alliance, true);
									return;
								}
							}
						}
					}
				}
            }
        }

		public static void tryNewArmyTreaty(Kingdom pKingdom)
		{
			if (pKingdom.civs_allies.Count > 0 && pKingdom.king != null)
			{
				if (!MoreGodPower.KingdomsTryArmy.ContainsKey(pKingdom) || MoreGodPower.KingdomsTryArmy[pKingdom].Count == 0 )
				{
					return;
				}
				if (MoreGodPower.AllianceKingdoms.ContainsKey(pKingdom) && MoreGodPower.AllianceKingdoms[pKingdom].Count > (actorStatus.diplomacy + 9) / 10)
				{
					MoreGodPower.KingdomsTryArmy[pKingdom].Clear();
					return;
				}
				foreach (Kingdom kingdom in MoreGodPower.KingdomsTryArmy[pKingdom])
				{
					if (pKingdom.civs_enemies.ContainsKey(kingdom))
					{
						MoreGodPower.KingdomsTryArmy[pKingdom].Remove(kingdom);
						break;
					}
                    if (MoreGodPower.AllianceKingdoms.ContainsKey(kingdom) && MoreGodPower.AllianceKingdoms[kingdom].Count > (actorStatus2.diplomacy + 9) / 10
						&& !MoreGodPower.AllianceKingdoms[kingdom].ContainsKey(pKingdom))
					{
						MoreGodPower.KingdomsTryArmy[pKingdom].Remove(kingdom);
						break;
                    }
					if (kingdom.king != null && !MoreGodPower.KingdomsOwnedByPlayer.Contains(kingdom))
					{
						actorStatus = Reflection.GetField(pKingdom.king.GetType(), pKingdom.king, "data") as ActorStatus;
						actorStatus2 = Reflection.GetField(kingdom.king.GetType(), kingdom.king, "data") as ActorStatus;
						chance = actorStatus.diplomacy * 30 / (actorStatus.diplomacy + actorStatus2.diplomacy);

						relation = MapBox.instance.kingdoms.diplomacyManager.getRelation(pKingdom, kingdom);
						relation.recalculate(pKingdom, kingdom);
						kingdomOpinion2 = MapBox.instance.kingdoms.diplomacyManager.getOpinion(kingdom, pKingdom);
						_opinion_total_2 = (int)Reflection.GetField(kingdomOpinion2.GetType(), kingdomOpinion2, "_opinion_total");

						if (_opinion_total_2 < 0)
						{
							chance /= 2;
						}
						if (Toolbox.randomInt(1, 100) < chance)
						{
							signNewTreaty(MoreGodPower.ArmyKingdoms, pKingdom, kingdom, "军事通行", 30, TreatyType.Army);
							signNewTreaty(MoreGodPower.AllianceKingdoms, pKingdom, kingdom, "互不侵犯", 30, TreatyType.Alliance, true, false);
							MoreGodPower.KingdomsTryArmy[pKingdom].Clear();
							return;
						}
						MoreGodPower.KingdomsTryArmy[pKingdom].Remove(kingdom);
						break;
					}
				}
			}
		}

		public static void tryNewDefenceTreaty(Kingdom pKingdom)
		{
			if (pKingdom.civs_allies.Count > 0 && pKingdom.king != null)
			{
				actorStatus = Reflection.GetField(pKingdom.king.GetType(), pKingdom.king, "data") as ActorStatus;
				if (MoreGodPower.AllianceKingdoms.ContainsKey(pKingdom) && MoreGodPower.AllianceKingdoms[pKingdom].Count > (actorStatus.diplomacy + 9) / 10)
				{
					return;
				}
				foreach (Kingdom kingdom in pKingdom.civs_allies.Keys)
				{
					if (kingdom.king != null && !MoreGodPower.KingdomsOwnedByPlayer.Contains(kingdom))
					{
						actorStatus2 = Reflection.GetField(kingdom.king.GetType(), kingdom.king, "data") as ActorStatus;
						if (!MoreGodPower.DefenceKingdoms.ContainsKey(kingdom) || MoreGodPower.DefenceKingdoms[kingdom].Count < (actorStatus2.diplomacy + 19) / 20)
						{
							relation = MapBox.instance.kingdoms.diplomacyManager.getRelation(pKingdom, kingdom);
							relation.recalculate(pKingdom, kingdom);

							kingdomOpinion = MapBox.instance.kingdoms.diplomacyManager.getOpinion(pKingdom, kingdom);
							_opinion_close_borders = (int)Reflection.GetField(kingdomOpinion.GetType(), kingdomOpinion, "_opinion_close_borders");
							_opinion_total = (int)Reflection.GetField(kingdomOpinion.GetType(), kingdomOpinion, "_opinion_power");

							kingdomOpinion2 = MapBox.instance.kingdoms.diplomacyManager.getOpinion(kingdom, pKingdom);
							_opinion_total_2 = (int)Reflection.GetField(kingdomOpinion2.GetType(), kingdomOpinion2, "_opinion_power");
							if (_opinion_close_borders < 0 && _opinion_total < 50 && _opinion_total_2 < 50)
							{
								chance = actorStatus.diplomacy * 10 / (actorStatus.diplomacy + actorStatus2.diplomacy);
								_opinion_total_2 = (int)Reflection.GetField(kingdomOpinion2.GetType(), kingdomOpinion2, "_opinion_total");
								if (_opinion_total_2 < 0)
								{
									chance /= 2;
								}
								if (Toolbox.randomInt(1, 100) < chance)
								{
									signNewTreaty(MoreGodPower.DefenceKingdoms, pKingdom, kingdom, "共同防御", 30, TreatyType.Defence);
									signNewTreaty(MoreGodPower.ArmyKingdoms, pKingdom, kingdom, "军事通行", 30, TreatyType.Army);
									signNewTreaty(MoreGodPower.AllianceKingdoms, pKingdom, kingdom, "互不侵犯", 30, TreatyType.Alliance, true, false);
									return;
								}
							}
						}
					}
				}
			}
		}

		public static void signNewTreaty(Dictionary<Kingdom, Dictionary<Kingdom, int>> treaty, Kingdom pKingdom, Kingdom tTarget, string text, int time, TreatyType type, bool clearDiplomacy = false, bool showText = true)
		{
			if (!treaty.ContainsKey(pKingdom))
			{
				treaty.Add(pKingdom, new Dictionary<Kingdom, int>());
			}
			if (!treaty.ContainsKey(tTarget))
			{
				treaty.Add(tTarget, new Dictionary<Kingdom, int>());
			}
			if (treaty[pKingdom].ContainsKey(tTarget))
			{
				treaty[pKingdom].Remove(tTarget);

			}
			if (treaty[tTarget].ContainsKey(pKingdom))
			{
				treaty[tTarget].Remove(pKingdom);

			}

			treaty[pKingdom].Add(tTarget, MapBox.instance.mapStats.year + time);
			treaty[tTarget].Add(pKingdom, MapBox.instance.mapStats.year + time);
			if (pKingdom.capital != null)
			{
				MoreGodPower.citiesCelebrate.Add(pKingdom.capital);
			}
			if (tTarget.capital != null)
			{
				MoreGodPower.citiesCelebrate.Add(tTarget.capital);
			}
			if (clearDiplomacy)
			{
				pKingdom.civs_allies.Remove(tTarget);
				tTarget.civs_allies.Remove(tTarget);
			}
            if (showText)
			{
				LogNewMessage(pKingdom, "与" + tTarget.name + "签订了" + text + "，期限" + time.ToString() + "年");
				LogNewMessage(tTarget, "与" + pKingdom.name + "签订了" + text + "，期限" + time.ToString() + "年");
			}
			message = pKingdom.id + "+" + tTarget.id + "+" + text;
			message2 = pKingdom.id + "+" + tTarget.id + "+" + text;
			newTreaty = new Treaty(pKingdom, tTarget, time, type, text);
			if (Main.treaties.ContainsKey(message) || Main.treaties.ContainsKey(message2))
			{
                if (Main.treaties.ContainsKey(message))
                {
					newTreaty = Main.treaties[message];
					Main.treaties.Remove(message);
				}
				if (Main.treaties.ContainsKey(message2))
				{
					newTreaty = Main.treaties[message2];
					Main.treaties.Remove(message2);
				}
            }
            else
			{
				newTreaty = new Treaty(pKingdom, tTarget, time, type, text);
			}
			Main.treaties.Add(message, newTreaty);
		}

		public static void updateTreaty(Dictionary<Kingdom, Dictionary<Kingdom, int>> treaty, string text, bool resetDiplomacy = false)
		{
			if (treaty.Count > 0)
			{
				foreach (var item in treaty)
				{
					if (!item.Key.alive)
					{
						if (item.Value.Count > 0)
						{
							foreach (var item2 in item.Value)
							{
								//清楚对方国家与己方的条约关系
								treaty[item2.Key].Remove(item.Key);
							}
							item.Value.Clear();
						}
						treaty.Remove(item.Key);
						return;
					}
					if (item.Value.Count > 0)
					{
						foreach (var item2 in item.Value)
						{
							if (item2.Value < MapBox.instance.mapStats.year)
							{
								designTreaty(treaty, item.Key, item2.Key, text, resetDiplomacy);
								return ;
							}
                            if (resetDiplomacy)
							{
								item.Key.civs_allies.Remove(item2.Key);
								item2.Key.civs_allies.Remove(item.Key);
							}
						}
					}
				}
			}

		}

		public static void designTreaty(Dictionary<Kingdom, Dictionary<Kingdom, int>> treaty, Kingdom kingdom1, Kingdom kingdom2, string text, bool resetDiplomacy = false)
		{
			if (!(treaty.ContainsKey(kingdom1) && treaty[kingdom1].ContainsKey(kingdom2)))
			{
				return;
			}
			if (resetDiplomacy)
			{
				kingdom1.civs_allies[kingdom2] = true;
				kingdom2.civs_allies[kingdom1] = true;
			}
			NewFunction.LogNewMessage(kingdom1, kingdom2, "", "与", "的" + text + "条约已过期");
			NewFunction.LogNewMessage(kingdom1, "与" + kingdom2.name + "的" + text + "条约已过期");
			NewFunction.LogNewMessage(kingdom2, "与" + kingdom1.name + "的" + text + "条约已过期");
			treaty[kingdom1].Remove(kingdom2);
			treaty[kingdom2].Remove(kingdom1);
			Main.treaties.Remove(kingdom1.id + "+" + kingdom2.id + "+" + text);
			Main.treaties.Remove(kingdom2.id + "+" + kingdom1.id + "+" + text);
		}
	}
}