using Gremlin.GremlinData.DBClasses;
using Gremlin.GremlinData.EntityClasses;
using Gremlin.GremlinUI;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace Gremlin.Models
{
    internal class RUSettingModel
    {
        private static readonly GremlinContext gremlinContext = new();

        private static Dictionary<string, string> ReadSettingsForRegisteredUserID(uint registeredUserID)
        {
            try
            {
                List<RUSetting> ruSettings = gremlinContext.RUSettings.Where(gC => gC.RegisteredUserID == registeredUserID).ToList();

                Dictionary<string, string> settings = new();

                foreach (RUSetting ruSetting in ruSettings)
                {
                    settings.Add(ruSetting.SettingKey, ruSetting.SettingValue);
                }

                return settings;
            }
            catch (Exception ex)
            {
                ErrorHandler.ShowErrorInMessageBox(ex);
                ChooseDB chooseDB = new();
                _ = chooseDB.ShowDialog();
                return ReadSettingsForRegisteredUserID(registeredUserID);
                throw;
            }
        }

        public static string GetSettingValue(uint registeredUserID, string settingKey)
        {
            try
            {
                Dictionary<string, string> rsfruid = ReadSettingsForRegisteredUserID(registeredUserID);
                if (!rsfruid.ContainsKey(settingKey) || rsfruid == null)
                {
                    Debug.WriteLine($"SettingKey {settingKey} not found or null!");
                    return "NotFound";
                }
                return rsfruid[settingKey];
            }
            catch (Exception ex)
            {
                ErrorHandler.ShowErrorInMessageBox(ex);
                return "RUSettings not valid";
                throw;
            }
        }

        public static void SetSettingValue(uint registeredUserID, string settingKey, string settingValue)
        {
            try
            {
                Dictionary<string, string> rsfruid = ReadSettingsForRegisteredUserID(registeredUserID);
                if (rsfruid.ContainsKey(settingKey)) rsfruid[settingKey] = settingValue;
                else rsfruid.Add(settingKey, settingValue);
            }
            catch (System.Exception ex)
            {
                ErrorHandler.ShowErrorInMessageBox(ex);
                throw;
            }
        }
    }
}
