using System;
using System.Collections.Generic;
using System.Linq;

namespace Mox.Shared.Serializer
{
	public class XmlSerializerSave : Serializer
	{
		public override bool Serialize(ref int _value, string _sName, int _defaultValue)
		{
			if (_value != _defaultValue)
			{
				m_sXml += " " + _sName + "=\"" + _value + "\"";
				return true;
			}

			return false;
		}

		public override bool Serialize(ref string _value, string _sName, string _defaultValue)
		{
			if (_value != _defaultValue)
			{
				m_sXml += " " + _sName + "=\"" + _value + "\"";
				return true;
			}

			return false;
		}

		public override bool Serialize(ref bool _value, string _sName, bool _defaultValue)
		{
			if (_value != _defaultValue)
			{
				m_sXml += " " + _sName + "=\"" + _value + "\"";
				return true;
			}

			return false;
		}

		public override bool StartChild(string _sName)
		{
			EndTag();
			m_lCurrentChild.Push(_sName);
			m_sXml += "<" + _sName;
			m_iCurrentIdent += 2;
			m_bChildless = true;
			return true;
		}

		private void EndTag()
		{
			if (m_lCurrentChild.Count == 0)
			{
				return;
			}

			m_sXml += ">\r\n" + new string(Enumerable.Range(0, m_iCurrentIdent).Select(i => ' ').ToArray());
		}

		public override void EndChild()
		{
			m_iCurrentIdent -= 2;
			var sName = m_lCurrentChild.Pop();
			if (m_bChildless)
			{
				m_sXml += " />";
			}
			else
			{
				m_sXml += "\r\n" + new string(Enumerable.Range(0, m_iCurrentIdent).Select(i => ' ').ToArray());
				m_sXml += "</" + sName + ">";
			}

			m_bChildless = false;
		}

		public override bool StartChild(string[] _aValidTags, out string _sName)
		{
			throw new NotImplementedException();
		}

		public override bool IsLoading => false;
		public string m_sXml;
		private readonly Stack<string> m_lCurrentChild = new Stack<string>();
		private int m_iCurrentIdent = 0;
		private bool m_bChildless;
	}
}
