using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Configuration;

using StackExchange;
using StackExchange.Redis;
using StackExchange.Redis.KeyspaceIsolation;

namespace OAuth2Study.Cache.RedisCache
{
    public sealed class RedisHelper
    {
        private static readonly Lazy<RedisHelper> lazy = new Lazy<RedisHelper>(() => new RedisHelper());

        private RedisHelper()
        {
        }

        private string connectString;

        public string ConnectString
        {
            get
            {
                if (connectString == null)
                {
                    connectString = ConfigurationManager.AppSettings["RedisConnectString"];
                }

                return connectString;
            }
            set
            {
                connectString = value;
            }
            
        }

        private IConnectionMultiplexer connectionMultiplexer;

        public IConnectionMultiplexer Multiplexer
        {
            get
            {
                if (connectionMultiplexer == null)
                {
                    ConfigurationOptions options=ConfigurationOptions.Parse(ConnectString);
                    options.AllowAdmin = true;

                    connectionMultiplexer=ConnectionMultiplexer.Connect(options);
                }

                return connectionMultiplexer;
            }

            set { connectionMultiplexer = value; }
        }

        public static RedisHelper Instance
        {
            get
            {
                return lazy.Value;
            }
        }

        public IDatabase GetDatabase(int dataIndex=15)
        {
            return Multiplexer.GetDatabase(dataIndex);
        }

        public List<IServer> GetServers()
        {
            List<IServer> servers = new List<IServer>();

            var points = Multiplexer.GetEndPoints();
            foreach (var point in points)
            {
                servers.Add(Multiplexer.GetServer(point));
            }
            return servers;
        }

        public IServer GetServer(System.Net.EndPoint endPoint)
        {
            var points = Multiplexer.GetEndPoints();
            var point = points.FirstOrDefault(p => p == endPoint);
            if (point != null)
            {
                return Multiplexer.GetServer(point);
            }
            else
            {
                return null;
            }
        }
    }
}