using System;
using System.Collections.ObjectModel;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace TimeScheduler.Domain.Impl
{
  /// <summary>Einfache Liste für die TimeItems</summary>
  /// <remarks>
  /// Implementierung der Schittstelle für die Xml-Serialisierung, weil es sonst zu Schlüsseln Fehler kommt.
  /// Implementierung von: http://weblogs.asp.net/pwelter34/444961
  /// </remarks>
  [Serializable]
  [XmlRoot("SimpleTimes")]
  public class SimpleTimes : KeyedCollection<int, TimeItem>, IXmlSerializable
  {
    #region Konstruktor
    /// <summary>Konstruktor</summary>
    public SimpleTimes() { }

    /// <inheritdoc/>
    protected override int GetKeyForItem(TimeItem item) { return item.Key; }
    #endregion

    #region IXmlSerializable
    /// <summary>Schema ermitteln</summary>
    /// <returns><c>null</c> im Standard</returns>
    public XmlSchema GetSchema() { return null; }

    /// <summary>Liest die Elemente aus dem XML-Stream</summary>
    /// <param name="reader">Der Steam-Leser</param>
    public void ReadXml(XmlReader reader)
    {

      //var keySerializer = new XmlSerializer(typeof(int));
      var valueSerializer = new XmlSerializer(typeof(TimeItem));

      var wasEmpty = reader.IsEmptyElement;
      reader.Read();
      
      if (wasEmpty)
        return;

      while (reader.NodeType != XmlNodeType.EndElement)
      {
        reader.ReadStartElement("item");

        //reader.ReadStartElement("key");
        //var key = (int)keySerializer.Deserialize(reader);
        //reader.ReadEndElement();

        reader.ReadStartElement("value");
        var value = (TimeItem)valueSerializer.Deserialize(reader);
        reader.ReadEndElement();

        Add(value);

        reader.ReadEndElement();
        reader.MoveToContent();
      }
      reader.ReadEndElement();
    }

    /// <summary>Schreibt die Elemente in den XML-Stream</summary>
    /// <param name="writer">Der Stream-Schreiber</param>
    public void WriteXml(XmlWriter writer)
    {
      //var keySerializer = new XmlSerializer(typeof(int));
      var valueSerializer = new XmlSerializer(typeof(TimeItem));

      foreach (var key in Dictionary.Keys)
      {
        writer.WriteStartElement("item");

        //writer.WriteStartElement("key");
        //keySerializer.Serialize(writer, key);
        //writer.WriteEndElement();

        writer.WriteStartElement("value");
        var value = this[key];
        valueSerializer.Serialize(writer, value);
        writer.WriteEndElement();

        writer.WriteEndElement();
      }
    }
    #endregion
  }
}
