using System.Xml;
using FluentNHibernate.MappingModel.Collections;
using FluentNHibernate.Utils;
using FluentNHibernate.Visitors;

namespace FluentNHibernate.MappingModel.Output
{
    public class XmlElementWriter : NullMappingModelVisitor, IXmlWriter<ElementMapping>
    {
        private readonly IXmlWriterServiceLocator serviceLocator;
        private XmlDocument document;

        public XmlElementWriter(IXmlWriterServiceLocator serviceLocator)
        {
            this.serviceLocator = serviceLocator;
        }

        public XmlDocument Write(ElementMapping mappingModel)
        {
            document = null;
            mappingModel.AcceptVisitor(this);
            return document;
        }

        public override void ProcessElement(ElementMapping mapping)
        {
            document = new XmlDocument();

            var element = document.AddElement("element");

            if (mapping.HasValue(x => x.Type))
                element.WithAtt("type", mapping.Type);

            if (mapping.HasValue(x => x.Length))
                element.WithAtt("length", mapping.Length);

            if (mapping.HasValue(x => x.Formula))
                element.WithAtt("formula", mapping.Formula);

            if (mapping.HasValue(x => x.Precision))
                element.WithAtt("precision", mapping.Precision);

            if (mapping.HasValue(x => x.Scale))
                element.WithAtt("scale", mapping.Scale);

            if (mapping.HasValue(x => x.NotNull))
                element.WithAtt("not-null", mapping.NotNull);

            if (mapping.HasValue(x => x.Unique))
                element.WithAtt("unique", mapping.Unique);
        }

        public override void Visit(ColumnMapping columnMapping)
        {
            var writer = serviceLocator.GetWriter<ColumnMapping>();
            var xml = writer.Write(columnMapping);

            document.ImportAndAppendChild(xml);
        }
    }
}