using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace SceneNPCEdit
{
	public static class SaveData
	{
		public static void Serialize(BinaryWriter binary)
		{
			binary.Write("CM3D2_NPCEDIT");
			binary.Write(1250);
			binary.Write(SaveData.presetData.Count);
			foreach (KeyValuePair<int, byte[]> keyValuePair in SaveData.presetData)
			{
				binary.Write(keyValuePair.Key);
				binary.Write(keyValuePair.Value.Length);
				binary.Write(keyValuePair.Value);
			}
		}

		public static void Deserialize(BinaryReader binary, int version)
		{
			SaveData.presetData.Clear();
			SaveData.presetDataCache.Clear();
			if (version < 1250)
			{
				return;
			}
			string a = binary.ReadString();
			NDebug.Assert(a == "CM3D2_NPCEDIT", "NPCEDITのヘッダーが不正です。");
			int num = binary.ReadInt32();
			int num2 = binary.ReadInt32();
			for (int i = 0; i < num2; i++)
			{
				int key = binary.ReadInt32();
				int count = binary.ReadInt32();
				byte[] value = binary.ReadBytes(count);
				if (!SaveData.presetData.ContainsKey(key))
				{
					SaveData.presetData.Add(key, value);
				}
			}
		}

		public static int GetID(CharacterMgr.NpcData targetNpcData)
		{
			foreach (EditCharacterDatabase.Data data in EditCharacterDatabase.GetAllDatas(true))
			{
				foreach (CharacterMgr.NpcData npcData in data.overRideTargetNpc)
				{
					if (npcData.uniqueName == targetNpcData.uniqueName)
					{
						return data.id;
					}
				}
			}
			return int.MinValue;
		}

		public static bool Contains(int id)
		{
			return SaveData.presetData.ContainsKey(id);
		}

		public static CharacterMgr.Preset GetPreset(int id)
		{
			CharacterMgr.Preset result = null;
			if (SaveData.presetDataCache.TryGetValue(id, out result))
			{
				return result;
			}
			if (SaveData.Contains(id))
			{
				byte[] buffer = SaveData.presetData[id];
				using (BinaryReader binaryReader = new BinaryReader(new MemoryStream(buffer), Encoding.UTF8))
				{
					CharacterMgr.Preset preset = GameMain.Instance.CharacterMgr.PresetLoad(binaryReader, string.Empty);
					SaveData.presetDataCache.Add(id, preset);
					result = preset;
				}
			}
			return result;
		}

		public static CharacterMgr.Preset GetPreset(CharacterMgr.NpcData npcData)
		{
			return SaveData.GetPreset(SaveData.GetID(npcData));
		}

		public static void SetPreset(int id, byte[] data)
		{
			SaveData.presetData[id] = data;
			if (SaveData.presetDataCache.ContainsKey(id))
			{
				SaveData.presetDataCache.Remove(id);
			}
		}

		public static void RemovePreset(int id)
		{
			SaveData.presetData.Remove(id);
			SaveData.presetDataCache.Remove(id);
		}

		public static Dictionary<int, byte[]> presetData = new Dictionary<int, byte[]>();

		public static Dictionary<int, CharacterMgr.Preset> presetDataCache = new Dictionary<int, CharacterMgr.Preset>();
	}
}
