using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Windows.Shapes;
using System.IO;
using System.Xml.Serialization;
using System.Windows.Input;

namespace VistaAdmin.Configuration.Models
{
    public class XmlDataSource : EnvironmentsList
    {
        private string source;

        public string Source
        {
            get
            {
                return this.source;
            }
            set
            {
                try
                {
                    Assembly executingAssembly = Assembly.GetExecutingAssembly();
                    string xmlFile = System.IO.Path.GetDirectoryName(executingAssembly.Location) + @"\DataSources\" + value;
                    this.source = xmlFile;

                    AddRange(RetrieveData(File.Open(xmlFile, FileMode.Open)));
                }
                catch (Exception ex)
                {
                    Log("Error occured retrieving data:" + ex.Message, System.Diagnostics.TraceEventType.Error);
                }
            }
        }

        public ICommand SaveCommand
        {
            get;
            set;
        }

        private EnvironmentsList RetrieveData(Stream xmlStream)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(EnvironmentsList));
            StreamReader reader = new StreamReader(xmlStream);
            EnvironmentsList list = (EnvironmentsList)serializer.Deserialize(reader);
            return list;
        }

        private static void Log(string message, System.Diagnostics.TraceEventType severity)
        {
            //LogEntry entry = new LogEntry();
            //entry.Severity = severity;
            //entry.Message = message;
            //entry.Title = "VistaAdminConfiguration";
            //entry.Categories.Add("Configuration");
            //Logger.Write(entry);
        }


        public void SaveData()
        {
            try
            {
                Assembly executingAssembly = Assembly.GetExecutingAssembly();
                string xmlFile = System.IO.Path.GetDirectoryName(executingAssembly.Location) + @"\DataSources\Environments.xml";

                XmlSerializer serializer = new XmlSerializer(typeof(EnvironmentsList));
                StreamWriter writer = new StreamWriter(xmlFile);
                serializer.Serialize(writer, this);
            }
            catch (Exception ex)
            {
                Log("Error trying to save Enviroment: " + ex.Message, System.Diagnostics.TraceEventType.Error);
            }
        }
    }
}
