using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

using Icarus.Resources;

namespace Icarus.Logic.GameEngine
{
    /// <summary>
    /// This class provides the functionality of being able to
    /// save and load levels.  The levels are saved as xml files
    /// on the harddrive.
    /// </summary>
    public class LevelLoader
    {

		#region Singleton access
		/// <summary>
		/// The instance of this loader
		/// </summary>
		private static LevelLoader instance = new LevelLoader();

        /// <summary>
        /// The Singleton LevelLoader instance
        /// </summary>
        public static LevelLoader Instance 
        {
            get { return instance; }
        } 

        #endregion

        #region Methods

        /// <summary>
        /// Loads a level from an XML file.
        /// </summary>
        /// <param name="fileName">The filename of the level XML file.</param>
        /// <returns>The loaded level or null if no level could be loaded.</returns>
        public Level LoadLevelXML(string fileName)
        {
            //Set the type of Object for deserialization
            Level level = new Level();
            XmlSerializer xmls = new XmlSerializer(level.GetType());

            //Open level XML file
            if (!File.Exists(fileName)) return null;
            FileStream fs = new FileStream(fileName, FileMode.Open);
            if(fs == null) return null;
    
            //read level file and create level
            XmlReader reader = new XmlTextReader(fs);
            level = (Level) xmls.Deserialize(reader);

            //Close file
            fs.Close();

            return level;
        }


        /// <summary>
        /// Saves a level to an XML file.
        /// </summary>
        /// <param name="fileName">The filename used to save the level XML file.</param>
        /// <returns>True for success, False for failure.</returns>
        public bool SaveLevelXML(string fileName, Level level)
        {
            //Setup serializer:
            XmlSerializer xmls = new XmlSerializer(level.GetType());
            
            //Create filestream to save level
            FileStream fs = new FileStream(fileName, FileMode.Create);
                        
            //Save level
            xmls.Serialize(fs, level);

            //Close file
            fs.Close();

            //return success;
            return true;
        }

		/// <summary>
		/// Returns the list of ids of available levels.
		/// </summary>
		/// <returns></returns>
		public string[] GetLevelIDList()
		{
			return Directory.GetFiles(ResourceManager.Instance.LevelPath, "*.xml");
		}

        #endregion

    }
}
