using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;

namespace Yuna.Website.Server.Infrastructure
{
    public static class Settings
    {
        public static TimeSpan AccessTokenLifeTime { get; private set; }
        public static TimeSpan RefreshTokenLifeTime { get; private set; }
        public static string ReferalCode { get; private set; } = null!;
        public static string DbConnectionStr { get; private set; } = null!;

        public static string HttpsExternalUrl { get; private set; } = null!;

        public static void Init()
        {
            var jsonText = File.ReadAllText("globalSettings.json");
            using JsonDocument document = JsonDocument.Parse(jsonText);

            var root = document.RootElement;


            var connectionStrs = root.GetProperty("ConnectionStrings");
            LoadConnectionStrs(connectionStrs);

            var externalLinkStrs = root.GetProperty("ExternalLinks");
            LoadExternalLinks(externalLinkStrs);

            var appVariablesStr = root.GetProperty("AppVariables");
            LoadAppVariables(appVariablesStr);


            string appName = AppDomain.CurrentDomain.FriendlyName;
            //DistributedCacheExtensions.Init(appName + "_");

        }


        private static void LoadConnectionStrs(JsonElement connectionStrs)
        {
            var env = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
            {

            }

            DbConnectionStr = connectionStrs.GetProperty("Db").GetString()!;
        }

        private static void LoadExternalLinks(JsonElement externalLinksStr)
        {
        }

        private static void LoadAppVariables(JsonElement appVariablesStr)
        {
            HttpsExternalUrl = appVariablesStr.GetProperty("HttpsExternalHost").GetString() ?? throw new Exception("no https exernal host");
            ReferalCode = appVariablesStr.GetProperty("ReferalCode").GetString() ?? throw new Exception("No ref code");
            AccessTokenLifeTime = TimeSpan.FromSeconds(appVariablesStr.GetProperty("AccessTokenLifeTimeMinutes").GetInt32());
            RefreshTokenLifeTime = TimeSpan.FromDays(appVariablesStr.GetProperty("RefreshTokenLifeTimeDays").GetInt32());
        }
    }
}
