using System;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;

namespace Agebull.EntityModel.Config
{
    /// <summary>
    /// À©Õ¹ÅäÖÃ½Úµã
    /// </summary>
    [DataContract, JsonObject(MemberSerialization.OptIn)]
    public partial class ConfigItemList
    {
        /// <summary>
        /// ¹¹Ôì
        /// </summary>
        /// <param name="items"></param>
        public ConfigItemList(NotificationList<ConfigItem> items)
        {
            Items = items;
        }

        /// <summary>
        /// ½Úµã£¨ÒýÓÃ£©
        /// </summary>
        public NotificationList<ConfigItem> Items { get; }

        /// <summary>
        /// ¶ÁÐ´À©Õ¹ÅäÖÃ
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string this[string key]
        {
            get
            {
                return string.IsNullOrWhiteSpace(key) ? null : Items.FirstOrDefault(p => p.Name == key)?.Value;
            }
            set
            {
                if (string.IsNullOrWhiteSpace(key))
                    return;
                var mv = Items.FirstOrDefault(p => p.Name == key);
                value = string.IsNullOrWhiteSpace(value) ? null : value.Trim();
                if (mv == null)
                {
                    Items.Add(new ConfigItem { Name = key, Value = value });
                }
                else
                {
                    mv.Value = value;
                }
            }
        }


        /// <summary>
        ///     Çå³ýÎÄ¼þÐÅÏ¢
        /// </summary>
        public void ClearFileConfig()
        {
            foreach (var kv in Items.Where(p => p.Name != null && p.Name.IndexOf("File_", StringComparison.OrdinalIgnoreCase) == 0).ToArray())
            {
                Items.Remove(kv);
            }
        }
        /// <summary>
        /// Çå³ýËùÓÐ
        /// </summary>
        public void Clear()
        {
            Items.Clear();
        }
    }
}