using System.ComponentModel;
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Primitives;
using static FSI.BT.IR.Plc.Settings.Log.Settings.Context;

namespace FSI.BT.IR.Plc.Settings.Log.Settings
{

    public class AppContext : ISettings
    {
        private Cfg _cfg;
        
        public AppContext()
        {        
            LoadSettings();
            LoadCfg();
        }

        private void LoadSettings()
        {
            var values = new ConfigurationBuilder()
              .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
              .Build();

            Settings = values.Get<Context.Settings>();
        }

        private void LoadCfg()
        {
            var values = new ConfigurationBuilder()
               .AddJsonFile("config.json", optional: true, reloadOnChange: true)
               .Build();

            Cfg = values.Get<Context.Cfg>();

            Action onChange = () =>
            {
                Cfg = values.Get<Context.Cfg>();
            };

            ChangeToken.OnChange(() => values.GetReloadToken(), onChange);
        }

        public Context.Settings Settings { get; set; }

        public Cfg Cfg
        {
            get { return _cfg; }
            set
            {
                _cfg = value;
                RaisePropertyChanged();
            }
        }

        private void RaisePropertyChanged([CallerMemberName] string propertyName = null)
        {
            // Null means no subscribers to the event
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}
