﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace Assets.BAndCCore.CustomTypes
{
	[Serializable]
	public class UserData
	{
		private AccountData m_accountData;
		private string m_emailAddress;

		public static string SubfolderName = "ServerData/Users/";
		public static string FileName = "UserData";

		public AccountData UserAccountData
		{
			get { return m_accountData; }
			set { m_accountData = value; }
		}

		public string EmailAddress
		{
			get { return m_emailAddress; }
			set { m_emailAddress = value; }
		}

		public UserData()
		{
		}

		public void SerializeUserData()
		{
			string userFolderPath = SubfolderName + m_accountData.Login + "/";

			XmlSerializer serializer = new XmlSerializer(this.GetType());

			if (!Directory.Exists(userFolderPath))
			{
				Directory.CreateDirectory(userFolderPath);
			}

			File.WriteAllText(userFolderPath + FileName, "");
			var writer = File.AppendText(userFolderPath + FileName);

			serializer.Serialize(writer, this);

			writer.Close();

			//Stream stream = new MemoryStream();
			//BinaryFormatter formatter = new BinaryFormatter();

			//formatter.Serialize(stream, this);

			//FileStream file = new FileStream(userFilesPath + m_accountData.Login, FileMode.Create, FileAccess.Write);
			//byte[] buffer = new byte[stream.Length];

			//stream.Read(buffer, 0, (int)stream.Length);
			//file.Write(buffer, 0, buffer.Length);

			//stream.Close();
			//file.Close();
		}

		public UserData Deserialize()
		{
			if (File.Exists(SubfolderName + m_accountData.Login + "/" + FileName))
			{
				string xmlData = File.ReadAllText(SubfolderName + m_accountData.Login + "/" + FileName);
				XmlSerializer serializer = new XmlSerializer(this.GetType());
				UserData data = (UserData)serializer.Deserialize(new StringReader(xmlData));

				return data;
			}
			else
			{
				return null;
			}
		}
	}
}