using Hydra.Framework.Data;
using System.Linq;

namespace Hydra.Framework.Configuration.Client
{
    /// <summary>
    /// Manage Client Configuration Settings
    /// </summary>
    public class SettingsManager :
        IReadWriteSettings
    {
        #region Member Variables
        /// <summary>
        /// Repository
        /// </summary>
        private IRepository repository;

        /// <summary>
        /// Environment String
        /// </summary>
        private string environment;

        /// <summary>
        /// Application String
        /// </summary>
        private string application;
        #endregion

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="SettingsManager"/> class.
        /// </summary>
        /// <param name="repository">The repository.</param>
        /// <param name="environment">The environment.</param>
        /// <param name="application">The application.</param>
        public SettingsManager(IRepository repository, string environment, string application)
        {
            this.repository = repository;
            this.environment = environment;
            this.application = application;
        }
        #endregion

        #region Public methods
        /// <summary>
        /// Gets the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public ISetting Get(string key)
        {
            // query by the environment id then by the application id lastly by the configuration key
            var result = repository.FindBy<SettingEntry>().Where(o => o.Key == key).First();
            return result;
        }
        #endregion

        #region IReadWriteSettings Implementation
        /// <summary>
        /// Puts the specified key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        public void Put(string key, string value)
        {
            //if it exists update 

            //else insert
            var setting = new SettingEntry()
                          {
                              Application = application,
                              Environment = environment,
                              Id = 0,
                              Key = key,
                              Value = value
                          };

            repository.Save(setting);
        }
        #endregion
    }
}