using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine;
using _Core;
using System.IO;
using System;

namespace _Combo
{
    public class Configuration : Serializable
    {
        [JsonProperty("distro")]
        public string Distro { get; private set; } = "";
        [JsonProperty("domains")]
        public List<string> Modules { get; private set; } = new List<string>();
        [JsonProperty("parameters")]
        public Dictionary<string, string> Parameters { get; private set; } = new Dictionary<string, string>();

        static readonly Configuration instance = Load();

        public static Configuration Instance => instance;
        private static Exception Exception;

        static Configuration Load()
        {
            TextAsset jsonFile = Resources.Load<TextAsset>("ComboSDK");
            if (jsonFile == null) {
                #if UNITY_EDITOR
                    return FromJson<Configuration>("{\"distro\":\"windows\",\"domains\":[\"seayoo_account\"],\"parameters\":{\"game_guest_auto_login_enabled\":\"false\",\"game_guest_enabled\":\"true\",\"sdk_unity_version\":\"0.1.0\",\"sdk_windows_version\":\"0.1.0\",\"seayoo_account_game_api_endpoint\":\"https://account-game-api.seayoo.com\"}}");
                #else
                    Exception = new FileNotFoundException("ComboSDK file not found");
                    Log.E(Exception);
                    return null;
                #endif
            }
            
            try
            {
                var settings = new JsonSerializerSettings
                {
                    MissingMemberHandling = MissingMemberHandling.Error,
                    Error = (sender, args) =>
                    {
                        args.ErrorContext.Handled = false;
                    }
                };
                return JsonConvert.DeserializeObject<Configuration>(jsonFile.text, settings);
            } catch (Exception ex)
            {
                Exception = ex;
                Log.E(Exception);
                return null;
            } 
        }
        
        public static Exception GetLastException()
        {
            return Exception;
        }
    }
}

