using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using CaLib.User;

namespace ClipClop.User
{
	public class ContextMenuSettingManager
	{
		public enum FileType
		{
			TreeXml,
			QtClip,
			Text,

		}; 
		
		
		XmlDocument document_;
		DateTime timeStamp_;

		public XmlDocument Document
		{
			get
			{
				return this.document_;
			}
			set
			{
				this.document_ = value;
			}
		}

		public XmlNode RootNode
		{
			get
			{
				return ContextMenuSettingHelper.GetRoot(this.document_);
			}
		}

		static IContextMenuReader GetReader(FileType type)
		{
			switch (type)
			{
				case FileType.TreeXml:
					return new XmlContextMenuReader();
				case FileType.QtClip:
					return new QtClipContextMenuReader();
			}

			throw new NotSupportedException();
		}

		/// <summary>
		/// 設定ファイルから、定義を読み込む。
		/// </summary>
		/// <param name="filePath"></param>
		/// <param name="type"></param>
		/// <returns>読み込んだかどうかを返す。エラーの場合は例外</returns>
		public bool Read(string filePath, ContextMenuSettingManager.FileType type)
		{
			FileInfo fi = new FileInfo(filePath);

			if (fi.Exists && timeStamp_ != fi.LastWriteTime)
			{
				try
				{
					IContextMenuReader reader = GetReader(type);

					timeStamp_ = fi.LastWriteTime;

					reader.Read(filePath);

					document_ = reader.GetDocument();
					return true;
				}
				catch
				{
					timeStamp_ = DateTime.MinValue;
					document_ = null;
					throw;//再送する。
				}
			}
			return false;
		}

        public void Write(string filePath)
        {
            if (document_ == null)
                throw new FundamentalException(global::ClipClop.Properties.Resources.EA001);
            document_.Save(filePath);
        }

	}
}
