﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace Oni.Level
{
    using Physics;

    partial class LevelImporter
    {
        private void ReadCameras(XmlReader xml, string basePath)
        {
            if (!xml.IsStartElement("Cameras"))
                return;

            if (xml.SkipEmpty())
                return;

            xml.ReadStartElement();

            while (xml.IsStartElement())
                ReadCamera(xml, basePath);

            xml.ReadEndElement();
        }

        private void ReadCamera(XmlReader xml, string basePath)
        {
            var filePath = Path.Combine(basePath, xml.GetAttribute("Path"));
            var scene = LoadScene(filePath);
            var clips = new List<ObjectAnimationClip>();

            if (filePath.Contains("Camout"))
            {
                Console.WriteLine(filePath);
            }

            ReadSequence(xml, "Camera", name =>
            {
                switch (name)
                {
                    case "Animation":
                        clips.Add(ReadAnimationClip(xml));
                        return true;

                    default:
                        return false;
                }
            });

            var props = new ObjectDaeNodeProperties();
            props.HasPhysics = true;
            props.Animations.AddRange(clips);

            var importer = new ObjectDaeImporter(null, new Dictionary<string, Akira.AkiraDaeNodeProperties> { { scene.Id, props } });

            importer.Import(scene);

            foreach (var node in importer.Nodes)
            {
                foreach (var animation in node.Animations)
                {
                    var writer = new DatWriter();
                    ObjectDatWriter.WriteAnimation(animation, writer);
                    writer.Write(outputDirPath);
                }
            }
        }

        private void ReadSequence(XmlReader xml, string name, Func<string, bool> action)
        {
            if (!xml.SkipEmpty())
            {
                xml.ReadStartElement(name);

                while (xml.IsStartElement())
                {
                    if (!action(xml.LocalName))
                    {
                        error.WriteLine("Unknown element {0}", xml.LocalName);
                        xml.Skip();
                    }
                }

                xml.ReadEndElement();
            }
        }
    }
}
