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

namespace MyScreenCap.Ctrl {

    /// <summary>
    /// Save Settings
    /// </summary>
    public static class SaveSettings {

        public static readonly string FILE_PATH = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Settings.xml");
        private const string XML_ROOT = "root";
        private const string KEY_NAME = "Value";

        /// <summary>
        /// 設定ファイルのLoad
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, string> Load() {
            Dictionary<string, string> settingDic = new Dictionary<string, string> { };
            try {
                XmlDocument xmlDoc = new XmlDocument();
                XmlNode xmlNode;
                xmlDoc.Load(FILE_PATH);
                xmlNode = xmlDoc.SelectSingleNode("//" + XML_ROOT);
                foreach (XmlElement elem in xmlNode) {
                    if (!settingDic.ContainsKey(elem.Name)) {
                        settingDic.Add(elem.Name, elem.GetAttribute(KEY_NAME));
                    }
                }
            } catch {
            }
            return settingDic;
        }

        /// <summary>
        /// 設定ファイルのSave
        /// </summary>
        /// <param name="settingDic">パラメータ名,Value のリスト</param>
        /// <returns>true:成功,false:失敗</returns>
        public static bool Save(Dictionary<string, string> settingDic) {
            if (settingDic == null) {
                return false;
            }

            try {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null));
                XmlElement rootElement = xmlDoc.CreateElement(XML_ROOT);
                xmlDoc.AppendChild(rootElement);
                foreach (KeyValuePair<string, string> setting in settingDic) {
                    XmlElement element = xmlDoc.CreateElement(setting.Key);
                    element.SetAttribute(KEY_NAME, setting.Value);
                    rootElement.AppendChild(element);
                }
                xmlDoc.Save(FILE_PATH);
                return true;
            } catch {
                return false;
            }
        }
    }
}
