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

namespace MegaManRipoff.MainGameClasses
{
    /// <summary>
    /// Reads a given levels XML document to see which levels exist. It then
    /// passes this information to MainGame so that it can cause a certain
    /// level to be loaded.
    /// </summary>
    class MainGameLoader
    {
        /// <summary>
        /// The name of the file that stores all of the levels that exist within
        /// the game.
        /// </summary>
        const string XmlName = "levels.xml";

        /// <summary>
        /// The path of the levels folder, ending with \\.
        /// </summary>
        string _levelsPath;

        /// <summary>
        /// Creates a new main game loader instance.
        /// </summary>
        /// <param name="levelsPath">The path of the levels folder, ending with \\.</param>
        public MainGameLoader(string levelsPath)
        {
            //Test that the path and relevant XML file exists.
            if (!File.Exists(levelsPath + XmlName))
                throw new Exception("The specified levels file \"" + levelsPath + XmlName +
                    "\" was not found.");

            _levelsPath = levelsPath;
        }

        /// <summary>
        /// Loads the each of the levels' folder names and XML document names from the
        /// levels XML document and returns them.
        /// </summary>
        /// <returns>Returns a list of level's folders and XML document names.</returns>
        public List<Tuple<string, string>> LoadLevelLocations()
        {
            //Create a new reader instance and load the XML file.
            XmlTextReader xmlTextReader = null;
            List<Tuple<string, string>> levelLocations = new List<Tuple<string, string>>();

            //Load the XML document.
            try
            {
                xmlTextReader = new XmlTextReader(_levelsPath + XmlName);

                //Iterate through all of the levels and read their details.
                while (xmlTextReader.ReadToFollowing("Level"))
                {
                    string levelFolderName, levelXmlName;

                    //If either of the folder or xml attributes are non-existent, don't
                    //load the level.
                    if ((levelFolderName = xmlTextReader.GetAttribute("folder")) != null
                        | (levelXmlName = xmlTextReader.GetAttribute("xml")) != null)
                    {
                        levelLocations.Add(new Tuple<string, string>(levelFolderName, levelXmlName));
                    }
                }
            }
            finally
            {
                //Close the reader if necessary.
                if (xmlTextReader != null)
                {
                    xmlTextReader.Close();
                }
            }

            return levelLocations;
        }
    }
}
