using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Xml;
using System.Data;
using System.IO;

namespace WriteXML
{
    public class WriteXML
    {
        public WriteXML()
        {
        }

        public void FlowHeater_SetDataTable(DataTable dt, StringDictionary parameter)
        {
            string Filename = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), parameter["Filename"]);
            string RecordName = parameter["RecordName"];                        

            XML.AppendChild(XML.CreateXmlDeclaration("1.0", null, null));

            XmlNode root = CreateNode("root");
            XML.AppendChild(root);

            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    XmlNode record = CreateNode(RecordName);
                    root.AppendChild(record);

                    foreach (DataColumn dl in dt.Columns)
                    {
                        XmlNode item = CreateNode(dl.ColumnName, dr[dl.ColumnName]);
                        record.AppendChild(item);
                    }
                }
            }

            XML.Save(Filename);

            string ShowXML = String.Empty;

            if (parameter.ContainsKey("ShowXML"))
                ShowXML = parameter["ShowXML"].ToUpper();

            if (ShowXML.Length > 1)
                ShowXML = ShowXML.Substring(0, 1);

            if (ShowXML == "1" || ShowXML == "Y" || ShowXML == "J")
                System.Diagnostics.Process.Start(Filename);
        }

        private XmlNode CreateNode(string name)
        {
            return CreateNode(name, null);
        }

        private XmlNode CreateNode(string name, object value)
        {
            XmlNode node = XML.CreateElement(name);
            SetNodeValue(node, value);

            return node;
        }

        private void SetNodeValue(XmlNode node, object value)
        {
            if (node == null || value == null)
                return;
            
            XmlText textnode = XML.CreateTextNode(value.ToString());                        
            node.AppendChild(textnode);
        }

        private XmlDocument m_XML = null;
        private XmlDocument XML
        {
            get
            {
                if (m_XML == null)
                    m_XML = new XmlDocument();

                return m_XML;
            }
        }
    }    
}
