using System;
using System.IO;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace MusicMetaTagger.UI
{
	/// <summary>
	///   Provides the user an interface for customizing program options
	/// </summary>
	internal partial class Options : Form, IDisposable
	{
		#region Private members

		private const string LIBRARY_QUERY_FILENAME = "options_libraryQuery.xml";

		private const string LIBRARY_UPDATE_FILENAME = "options_libraryUpdate.xml";
		private LibraryQuery _libraryQuery;

		private LibraryUpdate _libraryUpdate;

		#endregion

		#region Public Properties

		public LibraryQuery LibraryQuery
		{
			get { return _libraryQuery; }
			set { _libraryQuery = value; }
		}

		public LibraryUpdate LibraryUpdate
		{
			get { return _libraryUpdate; }
			set { _libraryUpdate = value; }
		}

		#endregion

		#region Constructor

		public Options()
		{
			InitializeComponent();
			// ConfigSectionObjects
			var optionsLoaded = false;
			if (File.Exists(LIBRARY_QUERY_FILENAME) && File.Exists(LIBRARY_UPDATE_FILENAME))
			{
				try
				{
					var libraryQuerySerializer = new XmlSerializer(typeof (LibraryQuery));
					using (TextReader textReader = new StreamReader(LIBRARY_QUERY_FILENAME))
					{
						_libraryQuery = (LibraryQuery) libraryQuerySerializer.Deserialize(textReader);
					}
					var libraryUpdateSerializer = new XmlSerializer(typeof (LibraryUpdate));
					using (TextReader textReader = new StreamReader(LIBRARY_UPDATE_FILENAME))
					{
						_libraryUpdate = (LibraryUpdate) libraryUpdateSerializer.Deserialize(textReader);
					}
					optionsLoaded = true;
				}
				catch
				{
				}
			}
			if (!optionsLoaded)
			{
				_libraryQuery = new LibraryQuery();
				_libraryUpdate = new LibraryUpdate();
			}
			libraryQueryPropertyGrid.SelectedObject = _libraryQuery;
			updatePropertyGrid.SelectedObject = _libraryUpdate;
		}

		#endregion

		#region Event Handlers

		private void Options_Load(object sender, EventArgs e)
		{
		}

		private void closeButton_Click(object sender, EventArgs e)
		{
			Hide();
		}

		#endregion

		#region IDisposable Members

		void IDisposable.Dispose()
		{
			var libraryQuerySerializer = new XmlSerializer(typeof (LibraryQuery));
			using (TextWriter textWriter = new StreamWriter(LIBRARY_QUERY_FILENAME))
			{
				libraryQuerySerializer.Serialize(textWriter, _libraryQuery);
			}
			var libraryUpdateSerializer = new XmlSerializer(typeof (LibraryUpdate));
			using (TextWriter textWriter = new StreamWriter(LIBRARY_UPDATE_FILENAME))
			{
				libraryUpdateSerializer.Serialize(textWriter, _libraryUpdate);
			}
		}

		#endregion
	}
}