using Newtonsoft.Json.Linq;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;

namespace Navigator.Utils
{
    public class AppSettingsManager
    {
        private static AppSettingsManager _instance;
//        private const string Namespace = "Navigator.Utils";
        private const string APP_SETTINGS = "Navigator.AppSettings.json";
        private JObject _secrets;
 
        private AppSettingsManager()
        {
            try
            {
                TypeInfo type=IntrospectionExtensions.GetTypeInfo(typeof(AppSettingsManager));
                Assembly assembly = type.Assembly;
                if(!assembly.GetManifestResourceNames().Any(x=>x.Equals(APP_SETTINGS)))return;
                Stream stream = assembly.GetManifestResourceStream(APP_SETTINGS);
   //             Stream stream = assembly.GetManifestResourceStream($"{Namespace}.{FileName}");
                using (var reader = new StreamReader(stream))
                {
                    var json = reader.ReadToEnd();
                    _secrets = JObject.Parse(json);
                }
            }
            catch (Exception exception)
            {
                Debug.WriteLine(String.Format("Unable to load AppSettings.json file {0}",exception.ToString()));
            }
        }
 
        public static AppSettingsManager Settings
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new AppSettingsManager();
                }
 
                return _instance;
            }
        }
 
        public string this[string name]
        {
            get
            {
                try
                {
                    var path = name.Split(':');
 
                    JToken node = _secrets[path[0]];
                    for (int index = 1; index < path.Length; index++)
                    {
                        node = node[path[index]];
                    }
 
                    return node.ToString();
                }
                catch (Exception)
                {
                    Debug.WriteLine($"Unable to retrieve item '{name}'");
                    return string.Empty;
                }
            }
        }
    }
}