
using dodohold.core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.FileSystemGlobbing.Internal;
using Spire.Pdf.Annotations;
using System.Text.RegularExpressions;
using System.Threading.Channels;
using System.Xml.Linq;
namespace molilian.core
{

    public partial class DeeplinkParseRuleCore
    {
        private static string _end_point;
        private static Dictionary<string, int> _calls = new();
        static DeeplinkParseRuleCore()
        {
            _end_point = Environment.GetEnvironmentVariable("EndPoint");
        }


        private static readonly object _lockObj = new();
        private static IEnumerable<DeeplinkParseRuleDTO> _cached;
        public static DeeplinkParseRuleDTO? GetOne(string channel)
        {
#if DEBUG
            var list = List(true);
#else
            var list = List();
#endif
            if (!list.Any()) return null;
            return list.Where(e => channel.Equals(e.channel_name)).FirstOrDefault();
        }

        public static IEnumerable<DeeplinkParseRuleDTO> List(bool force = false)
        {
            if (!force && _cached != null) return _cached;

            string cache_key = $"cache:deeplink_parse_rule";
            var list = RedisHelper.Get<IEnumerable<DeeplinkParseRuleDTO>>(cache_key);
            if (force || list == null)
            {
                lock (_lockObj)
                {
                    list = new DBContext.Table("deeplink_parse_rule")
                        .Where("status=@status", new { status = 1 })
                        .Select<DeeplinkParseRuleDTO>();
                    if (list == null) return default;

                    RedisHelper.Set(cache_key, list, 30 * 86400);
                }
            }
            _cached = list;
            return list;
        }

        public static void Refresh()
        {
            _ = List(true);
        }

        public static async Task<int> Update(DeeplinkParseRuleDTO rule)
        {
            var conn = DBContext.GetOpenConnection();
            return await conn.UpdateAsync<DeeplinkParseRuleDTO>(rule);
        }

    }
}