using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Siger.Middlelayer.Redis.RedisEntities;

namespace Siger.Middlelayer.Redis
{
    public partial class RedisCache
    {
        private const string HostHash = "Hosts";

        public IEnumerable<HostEntity> GetHosts()
        {
            var hosts = new List<HostEntity>();
            var allHosts = Client.HGetAll(HostHash);
            foreach (var host in allHosts)
            {
                var cidpid = host.Key.Split(':');
                hosts.Add(new HostEntity
                {
                    Host = cidpid[0],
                    Port = cidpid.Length > 1 ? cidpid[1] : ""
                });
            }

            return hosts;
        }

        public void AddHost(HostEntity host)
        {
            var key = $"{host.Host}:{host.Port}";

            Client.HSet(HostHash, key, 1);
        }

        public void DeleteHost(string key)
        {
            Client.HDel(HostHash, key);
        }

        /// <summary>
        /// get all allow origins
        /// </summary>
        /// <returns></returns>
        public List<string> AllowOrigins()
        {
            var allHosts = Client.HGetAll(HostHash);
            if (allHosts != null)
            {
                return allHosts.Where(q => q.Value == "1").Select(host => host.Key.StartsWith("http") ? host.Key : $"http://{host.Key}").ToList();
            }
            return new List<string>();
        }

    }
}
