﻿using System;
using System.Collections.Generic;
using System.Xml;

namespace Oni.Xml
{
    internal class TmbdXmlImporter : RawXmlImporter
    {
        private TmbdXmlImporter(XmlReader reader, BinaryWriter writer)
            : base(reader, writer)
        {
        }

        public static void Import(XmlReader reader, BinaryWriter writer)
        {
            var importer = new TmbdXmlImporter(reader, writer);
            importer.Import();
        }

        private void Import()
        {
            Writer.Write(1);
            int countPosition = Writer.Position;
            Writer.Write(0);

            var materials = new Dictionary<string, List<string>>();

            while (Xml.IsStartElement("Material"))
            {
                string materialName = Xml.GetAttribute("Name");

                Xml.ReadStartElement();

                while (Xml.IsStartElement("Texture"))
                {
                    string textureName = Xml.ReadElementContentAsString();

                    List<string> textures;

                    if (!materials.TryGetValue(materialName, out textures))
                    {
                        textures = new List<string>();
                        materials.Add(materialName, textures);
                    }

                    textures.Add(textureName);
                }

                Xml.ReadEndElement();
            }

            int count = 0;

            foreach (var pair in materials)
            {
                foreach (string textureName in pair.Value)
                {
                    Writer.Write(pair.Key, 32);
                    Writer.Write(textureName, 32);

                    count++;
                }
            }

            Writer.WriteAt(countPosition, count);
        }
    }
}
