using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.IO;

namespace Grovewood
{
    class xml
    {
        /**************************************************
        * 
        *    XML Get System :: GetXML(File, Field)
        * 
        * ************************************************/

        public static string GetXML(string File, string Field)
        {
            try
            {

                string value = "";
                //Console.WriteLine("IN GetXMLValue");
                //string path = FileName;
                XmlDocument doc = new XmlDocument();
                doc.Load(File);

                XmlNode xmlnde = doc.DocumentElement.SelectSingleNode(Field);
                value = xmlnde.InnerText;
                return value;
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to retrive value, Reason: " + e.ToString());
                return "";
            }
        }

        /**************************************************
         * 
         *    XML Update System :: UpdateXML(File, Field, Value)
         * 
         * ************************************************/
        public static string UpdateXML(string File, string field, string value)
        {
            try
            {
                string path = @File;
                //Open the file for Editing.
                XmlDocument doc = new XmlDocument();
                doc.Load(path);
                //Ok, its loaded, now we need to find the Element we want to edit.
                XmlNode xmlNde = doc.DocumentElement.SelectSingleNode(@field);
                if (xmlNde == null)
                {
                    XmlElement root = doc.DocumentElement;
                    XmlElement elmNew = doc.CreateElement(field);
                    XmlText txt = doc.CreateTextNode(value);
                    root.AppendChild(elmNew);
                    root.LastChild.AppendChild(txt);
                }
                else
                {
                    //Set the new value.
                    xmlNde.InnerText = value;
                }
                //Save changes.
                doc.Save(path);
                return "Field sucessfully updated to a value of: " + value + " In File: " + File;
            }
            catch (Exception e)
            {
                //Console.WriteLine("Field does not exist.");
                return "Failed, Reason: " + e.ToString();
            }
        }

        /********************************
         * 
         *   Create XML :: CreateXML(FileName, 2d String Array, RootElement, Comment)
         *   CreateXML(Prey.xml, myPrey, PreyName, PreyFile for PREY);
         *   
         * ******************************/

        public static string CreateXML(string FileName, string[,] mA, string RootElement, string Comment, int Elements)
        {
            try
            {
                XmlTextWriter xW = new XmlTextWriter(FileName, null);
                xW.WriteStartDocument();

                //So a comment for the file can be added.
                xW.WriteComment(Comment);

                //First Element, Root Element
                xW.WriteStartElement(RootElement);

                //Use a loop to populate the fields.
                int i = 0;
                for (i = 0; i <= Elements; i++)
                {
                    xW.WriteElementString(mA[i, 0], mA[i, 1]);
                }
                xW.WriteEndElement();
                xW.WriteEndDocument();
                xW.Close();
                Console.WriteLine("Generated XML: " + FileName);
                return "Sucessfully created XML File: " + FileName;
            }
            catch (Exception e)
            {
                return "Failed to create XML File: " + FileName + " Reason: " + e.ToString();
            }
        }

        /********************************
        * 
        *   AppendElement :: AppendElement(FileName, Field, InitialValue)
        *   AppendElement(Wolf.xml, cHP, 100);
        *   Adds an Element to the end of the specified XML file.
        *   
        * ******************************/

        public static string AppendElement(string FileName, string Field, string Value)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                if (File.Exists(FileName))
                {
                    doc.Load(FileName);
                    XmlElement root = doc.DocumentElement;
                    XmlElement elmNew = doc.CreateElement(Field);
                    XmlText txt = doc.CreateTextNode(Value);
                    root.AppendChild(elmNew);
                    root.LastChild.AppendChild(txt);

                    doc.Save(FileName);
                    return "Success - Appended Field:" + Field + " with a Value of: " + Value + " To File: " + FileName;
                }
                else
                {
                    return FileName + " Does not Exist";
                }
                
            }
            catch (Exception e)
            {
                return "Failed: " + e.ToString();
            }
        }

        public static int Countelements(string File)
        {
            int elements = 0;


            return elements;
        }

        //Sort the XML File

        public static bool SortXML(string File)
        {
            try
            {
                //int Elements = 0;
                int Count = 0;
                int Loops = Convert.ToInt32(xml.GetXML("./help/" + File + ".xml", "HelpCount"));
                string[] MyInventory = new string[Loops];
                string[] Problems = new string[Loops];


                for (int i = 1; i <= Loops; i++)
                {
                    if (xml.GetXML("./help/" + File + ".xml", "Help_" + i) != "#CLOSED#")
                    {
                        MyInventory[Count + 1] = xml.GetXML("./help/" + File + ".xml", "Help_" + i);
                        Problems[Count + 1] = xml.GetXML("./help/" + File + ".xml", "Help_" + i + "_Problem");
                        Count++;
                    }
                }

                //Update the fields
                if (Count >= 1)
                {
                    for (int i = 1; i <= Count; i++)
                    {
                        xml.UpdateXML("./help/" + File + ".xml", "Help_" + i, MyInventory[i]);
                        xml.UpdateXML("./help/" + File + ".xml", "Help_" + i + " _Problem", Problems[i]);
                    }
                }

                xml.UpdateXML("./help/" + File + ".xml", "HelpCount", Count.ToString());

                return true;
            }
            catch (Exception sort)
            {
                //if (irc.debug == true)
                //{
                Console.WriteLine("(XML-Sort) Error : " + sort.ToString());
               //     irc_functions.ErrorLog("Could not sort XML : " + sort.ToString(), "XML");
                //}
                return false;
            }
        }
    }
}
