using System;
using System.IO;
using System.Xml.Linq;
using UnityEngine;
using wf;

public class PhotoModeSaveAndLoad : MonoBehaviour
{
	public string folder_path
	{
		get
		{
			return this.folder_path_;
		}
		set
		{
			if (!Directory.Exists(value))
			{
				Directory.CreateDirectory(value);
			}
			this.folder_path_ = value;
		}
	}

	public void Awake()
	{
		NDebug.Assert(0 < this.Pages, "pages error.");
		EventDelegate.Add(UTY.GetChildObject(base.gameObject, "Cancel", false).GetComponent<UIButton>().onClick, new EventDelegate.Callback(this.Close));
		for (int i = 1; i <= this.Pages; i++)
		{
			GameObject gameObject = Utility.CreatePrefab(this.PageButtonParent.gameObject, "SceneDaily/SaveAndLoad/Prefab/PhotSaveLoagPageBtn", true);
			UIWFTabButton component = gameObject.GetComponent<UIWFTabButton>();
			component.gameObject.name = i.ToString();
			component.normalSprite = "cm3d2_save_load_page" + i.ToString("d2");
			EventDelegate.Add(component.onSelect, new EventDelegate.Callback(this.OnClickPageBtn));
		}
		this.PageButtonParent.Reposition();
		this.PageButtonParent.GetComponent<UIWFTabPanel>().UpdateChildren();
		this.data_unit_ = new PhotSaveLoagDataUnit[6];
		for (int j = 0; j < this.data_unit_.Length; j++)
		{
			GameObject gameObject2 = Utility.CreatePrefab(this.DataUnitParent.gameObject, "SceneDaily/SaveAndLoad/Prefab/PhotSaveLoagDataUnit", true);
			gameObject2.name = j.ToString();
			this.data_unit_[j] = gameObject2.GetComponent<PhotSaveLoagDataUnit>();
			this.data_unit_[j].visible_content = false;
			this.data_unit_[j].onClick = new Action<PhotSaveLoagDataUnit>(this.OnClickDataUnit);
			this.data_unit_[j].onChangeTitle = new Action<PhotSaveLoagDataUnit>(this.OnChangeTitle);
			this.data_unit_[j].onChangeComment = new Action<PhotSaveLoagDataUnit>(this.OnChangeComment);
		}
		EventDelegate.Add(UTY.GetChildObject(base.gameObject, "DisplayButtonGroup/DisplaySave", false).GetComponent<UIButton>().onClick, delegate()
		{
			this.ChangeType((this.cur_type_ != PhotoModeSaveAndLoad.Type.Save) ? PhotoModeSaveAndLoad.Type.Save : PhotoModeSaveAndLoad.Type.Load);
			this.UpdateDataUnit();
		});
		EventDelegate.Add(UTY.GetChildObject(base.gameObject, "DisplayButtonGroup/DisplayLoad", false).GetComponent<UIButton>().onClick, delegate()
		{
			this.ChangeType((this.cur_type_ != PhotoModeSaveAndLoad.Type.Save) ? PhotoModeSaveAndLoad.Type.Save : PhotoModeSaveAndLoad.Type.Load);
			this.UpdateDataUnit();
		});
		this.ChangeType(PhotoModeSaveAndLoad.Type.Save);
		this.PageButtonParent.GetComponent<UIWFTabPanel>().Select(this.PageButtonParent.GetChild(0).GetComponent<UIWFTabButton>());
	}

	public void Start()
	{
	}

	public void Open(bool is_save_mode)
	{
		if (this.is_fade_processed)
		{
			return;
		}
		UICamera[] array = NGUITools.FindActive<UICamera>();
		foreach (UICamera uicamera in array)
		{
			UIPanel component = uicamera.transform.parent.GetComponent<UIPanel>();
			if (0 <= component.name.ToLower().IndexOf("fix"))
			{
				component.alpha = 0f;
			}
		}
		base.gameObject.SetActive(true);
		this.ChangeType((!is_save_mode) ? PhotoModeSaveAndLoad.Type.Load : PhotoModeSaveAndLoad.Type.Save);
		this.UpdateDataUnit();
		TweenAlpha tweenAlpha = base.gameObject.AddComponent<TweenAlpha>();
		tweenAlpha.from = 0f;
		tweenAlpha.to = 1f;
		tweenAlpha.duration = 0.3f;
		tweenAlpha.PlayForward();
		EventDelegate.Set(tweenAlpha.onFinished, delegate()
		{
			TweenAlpha component2 = base.gameObject.GetComponent<TweenAlpha>();
			if (component2 != null)
			{
				UnityEngine.Object.DestroyImmediate(component2);
			}
		});
	}

	public void Close()
	{
		if (this.is_fade_processed)
		{
			return;
		}
		UICamera[] array = NGUITools.FindActive<UICamera>();
		foreach (UICamera uicamera in array)
		{
			UIPanel component = uicamera.transform.parent.GetComponent<UIPanel>();
			if (0 <= component.name.ToLower().IndexOf("fix"))
			{
				component.alpha = 1f;
			}
		}
		TweenAlpha tweenAlpha = base.gameObject.AddComponent<TweenAlpha>();
		tweenAlpha.from = 1f;
		tweenAlpha.to = 0f;
		tweenAlpha.duration = 0.3f;
		tweenAlpha.PlayForward();
		EventDelegate.Set(tweenAlpha.onFinished, delegate()
		{
			TweenAlpha component2 = base.gameObject.GetComponent<TweenAlpha>();
			if (component2 != null)
			{
				UnityEngine.Object.DestroyImmediate(component2);
			}
			base.gameObject.SetActive(false);
		});
	}

	public void OnEnable()
	{
		this.CreateThumbnail();
	}

	private void Update()
	{
		if (string.IsNullOrEmpty(this.thum_byte_to_base64_) && File.Exists(this.thum_file_path_))
		{
			Texture2D texture2D = new Texture2D(1, 1, TextureFormat.ARGB32, false);
			texture2D.LoadImage(File.ReadAllBytes(this.thum_file_path_));
			float num = (float)texture2D.width / (float)texture2D.height;
			Vector2 vector = new Vector2(480f, 270f);
			int num2 = texture2D.width;
			int num3 = texture2D.height;
			if (vector.x < (float)texture2D.width && vector.y < (float)texture2D.height)
			{
				num2 = (int)vector.x;
				num3 = Mathf.RoundToInt((float)num2 / num);
				if (vector.y < (float)num3)
				{
					num3 = (int)vector.y;
					num2 = Mathf.RoundToInt((float)num3 * num);
				}
			}
			else if (vector.x < (float)texture2D.width)
			{
				num2 = (int)vector.x;
				num3 = Mathf.RoundToInt((float)num2 / num);
			}
			else if (vector.y < (float)texture2D.height)
			{
				num3 = (int)vector.y;
				num2 = Mathf.RoundToInt((float)num3 * num);
			}
			TextureScale.Bilinear(texture2D, num2, num3);
			this.thum_byte_to_base64_ = Convert.ToBase64String(texture2D.EncodeToPNG());
			UnityEngine.Object.DestroyImmediate(texture2D);
		}
	}

	private void ChangeType(PhotoModeSaveAndLoad.Type type)
	{
		if (type == PhotoModeSaveAndLoad.Type.Save)
		{
			UTY.GetChildObject(base.gameObject, "DisplayButtonGroup/DisplaySave", false).SetActive(false);
			UTY.GetChildObject(base.gameObject, "DisplayButtonGroup/DisplayLoad", false).SetActive(true);
			UTY.GetChildObject(base.gameObject, "TitleGroup/TitleSave", false).SetActive(true);
			UTY.GetChildObject(base.gameObject, "TitleGroup/TitleLoad", false).SetActive(false);
		}
		else
		{
			UTY.GetChildObject(base.gameObject, "DisplayButtonGroup/DisplaySave", false).SetActive(true);
			UTY.GetChildObject(base.gameObject, "DisplayButtonGroup/DisplayLoad", false).SetActive(false);
			UTY.GetChildObject(base.gameObject, "TitleGroup/TitleSave", false).SetActive(false);
			UTY.GetChildObject(base.gameObject, "TitleGroup/TitleLoad", false).SetActive(true);
		}
		this.cur_type_ = type;
	}

	public string GetFileName(int page_no, int unit_no)
	{
		return string.Concat(new string[]
		{
			"SaveData_",
			page_no.ToString("d2"),
			"_",
			(unit_no + 1).ToString("d2"),
			".xml"
		});
	}

	public string GetSaveFullPath(int page_no, int unit_no)
	{
		return Path.Combine(this.folder_path, this.GetFileName(page_no, unit_no));
	}

	private void CreateThumbnail()
	{
		this.thum_byte_to_base64_ = string.Empty;
		this.thum_file_path_ = Path.Combine(Path.GetTempPath(), "cm3d2_" + Guid.NewGuid().ToString() + ".png");
		GameMain.Instance.MainCamera.ScreenShot(this.thum_file_path_, 1, true);
	}

	private void OnClickDataUnit(PhotSaveLoagDataUnit unit)
	{
		if (this.is_fade_processed)
		{
			return;
		}
		string save_path = this.GetSaveFullPath(this.cur_page_no_, int.Parse(unit.name));
		if (UICamera.currentTouchID == -2)
		{
			if (unit.save_data_object == null)
			{
				return;
			}
			if (GameMain.Instance.SysDlg.IsDecided)
			{
				GameMain.Instance.SysDlg.Show("データを削除しますが宜しいですか？", SystemDialog.TYPE.OK_CANCEL, delegate
				{
					GameMain.Instance.SysDlg.Close();
					this.RemoveSave(save_path);
					this.UpdateDataUnit(unit);
				}, null);
			}
		}
		else if (UICamera.currentTouchID == -1)
		{
			if (this.cur_type_ == PhotoModeSaveAndLoad.Type.Save)
			{
				if (unit.save_data_object != null)
				{
					if (GameMain.Instance.SysDlg.IsDecided)
					{
						GameMain.Instance.SysDlg.Show("上書きして保存しますが宜しいですか？", SystemDialog.TYPE.OK_CANCEL, delegate
						{
							GameMain.Instance.SysDlg.Close();
							this.WriteSave(save_path, unit.title, unit.comment);
							this.UpdateDataUnit(unit);
						}, null);
					}
				}
				else
				{
					this.WriteSave(save_path, string.Empty, string.Empty);
					this.UpdateDataUnit(unit);
				}
			}
			else
			{
				if (unit.save_data_object == null)
				{
					return;
				}
				if (GameMain.Instance.SysDlg.IsDecided)
				{
					GameMain.Instance.SysDlg.Show("データをロードしますか？", SystemDialog.TYPE.OK_CANCEL, delegate
					{
						GameMain.Instance.SysDlg.Close();
						this.ReadSave(save_path);
						this.Close();
					}, null);
				}
			}
		}
	}

	public void WriteSave(string save_full_path, string title, string comment)
	{
		XDocument xdocument = this.WriteSaveToXdocument(title, comment);
		xdocument.Save(save_full_path);
	}

	public XDocument WriteSaveToXdocument(string title, string comment)
	{
		XElement xelement = this.CreateCommonData(title, comment);
		XElement xelement2 = null;
		if (this.onSerializeEvent != null)
		{
			xelement2 = this.onSerializeEvent();
		}
		return new XDocument(new XDeclaration("1.0", "utf-8", "true"), new object[]
		{
			new XComment("CM3D2 PhotModeSaveData"),
			new XElement("Data", new object[]
			{
				xelement2,
				xelement
			})
		});
	}

	public void ReadSave(string save_full_path)
	{
		if (!File.Exists(save_full_path))
		{
			return;
		}
		this.ReadSave(XDocument.Load(save_full_path));
	}

	public void ReadSave(byte[] saveBinary)
	{
		using (MemoryStream memoryStream = new MemoryStream(saveBinary))
		{
			this.ReadSave(XDocument.Load(memoryStream));
		}
	}

	public void ReadSave(XDocument xml)
	{
		if (this.onDeserializeEvent != null)
		{
			this.onDeserializeEvent(xml.Element("Data"));
		}
	}

	private void RemoveSave(string save_full_path)
	{
		if (!File.Exists(save_full_path))
		{
			return;
		}
		try
		{
			File.Delete(save_full_path);
		}
		catch (Exception ex)
		{
			Debug.LogWarning("削除失敗 " + ex.Message);
		}
	}

	private void OnChangeTitle(PhotSaveLoagDataUnit unit)
	{
		if (unit == null || unit.save_data_object == null)
		{
			return;
		}
		XDocument xdocument = unit.save_data_object as XDocument;
		XElement xelement = xdocument.Element("Data").Element("Common");
		XElement xelement2 = xelement.Element("Title");
		if (xelement2 != null && xelement2.Value != UIInput.current.value)
		{
			xelement2.SetValue(UIInput.current.value);
			xdocument.Save(this.GetSaveFullPath(this.cur_page_no_, int.Parse(unit.name)));
		}
	}

	private void OnChangeComment(PhotSaveLoagDataUnit unit)
	{
		if (unit == null || unit.save_data_object == null)
		{
			return;
		}
		XDocument xdocument = unit.save_data_object as XDocument;
		XElement xelement = xdocument.Element("Data").Element("Common");
		XElement xelement2 = xelement.Element("Comment");
		if (xelement2 != null && xelement2.Value != UIInput.current.value)
		{
			xelement2.SetValue(UIInput.current.value);
			xdocument.Save(this.GetSaveFullPath(this.cur_page_no_, int.Parse(unit.name)));
		}
	}

	private void OnClickPageBtn()
	{
		if (!UIWFSelectButton.current.isSelected)
		{
			return;
		}
		this.cur_page_no_ = int.Parse(UIWFSelectButton.current.gameObject.name);
		this.UpdateDataUnit();
	}

	public void OnClickBG()
	{
		if (this.is_fade_processed)
		{
			return;
		}
		if (UICamera.currentTouchID == -2)
		{
			this.Close();
		}
	}

	private void UpdateDataUnit()
	{
		if (this.cur_page_no_ < 0)
		{
			return;
		}
		for (int i = 0; i < this.data_unit_.Length; i++)
		{
			this.UpdateDataUnit(this.data_unit_[i]);
		}
	}

	private void UpdateDataUnit(PhotSaveLoagDataUnit unit)
	{
		string text = Path.Combine(this.folder_path, this.GetFileName(this.cur_page_no_, Array.IndexOf<PhotSaveLoagDataUnit>(this.data_unit_, unit)));
		if (File.Exists(text))
		{
			XDocument xdocument = XDocument.Load(text);
			unit.save_data_object = xdocument;
			unit.visible_content = true;
			XElement xmle = xdocument.Element("Data").Element("Common");
			unit.date_text = Xml.GetElement(xmle, "SaveTime", string.Empty);
			unit.title = Xml.GetElement(xmle, "Title", string.Empty);
			unit.comment = Xml.GetElement(xmle, "Comment", string.Empty);
			unit.maid_count = int.Parse(Xml.GetElement(xmle, "MaidCount", "0"));
			string element = Xml.GetElement(xmle, "Thumbnail", string.Empty);
			if (!string.IsNullOrEmpty(element))
			{
				unit.thumbnail = Convert.FromBase64String(element);
			}
			else
			{
				unit.thumbnail = null;
			}
		}
		else
		{
			unit.save_data_object = null;
			unit.visible_content = false;
		}
		if (this.cur_type_ == PhotoModeSaveAndLoad.Type.Load && unit.save_data_object == null)
		{
			unit.enabled_button = false;
		}
		else
		{
			unit.enabled_button = true;
		}
	}

	private XElement CreateCommonData(string title, string comment)
	{
		string value = DateTime.ParseExact(DateTime.Now.ToString("yyyyMMddHHmmss"), "yyyyMMddHHmmss", null).ToString("yyyy.MM.dd HH:mm");
		XElement xelement = new XElement("GameVersion", 1170);
		XElement xelement2 = new XElement("SaveTime", value);
		XElement xelement3 = new XElement("Title", title);
		XElement xelement4 = new XElement("Comment", comment);
		XElement xelement5 = new XElement("MaidCount", this.PhotoMgr.GetActiveMaidCount().ToString());
		XComment xcomment = new XComment("encoding png image at base64.");
		XElement xelement6 = new XElement("Thumbnail", this.thum_byte_to_base64_);
		XNode[] contents = new XNode[]
		{
			xelement2,
			xelement3,
			xelement4,
			xelement5,
			xcomment,
			xelement6
		};
		return new XElement("Common", contents);
	}

	private bool is_fade_processed
	{
		get
		{
			TweenAlpha component = base.gameObject.GetComponent<TweenAlpha>();
			if (component != null && !component.enabled)
			{
				component.enabled = true;
			}
			return component != null;
		}
	}

	public PhotoWindowManager PhotoMgr;

	public LoadReplaceMaid LoadReplaceMaidPanel;

	public UIGrid PageButtonParent;

	public int Pages;

	public UITable DataUnitParent;

	public Func<XElement> onSerializeEvent;

	public Action<XElement> onDeserializeEvent;

	private PhotSaveLoagDataUnit[] data_unit_;

	private int cur_page_no_;

	private PhotoModeSaveAndLoad.Type cur_type_;

	private string folder_path_;

	private string thum_file_path_;

	private string thum_byte_to_base64_ = string.Empty;

	private enum Type
	{
		Save,
		Load
	}
}
