using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Foresight.Cache;
using Foresight.Service.Cache;
using Foresight.Fleet.Services.SystemOption;

namespace IronIntel.Contractor
{
    public static class CacheManager
    {
        private static CacheClient _Client = null;
        private static object _sycobj = new object();

        private static CacheClient CreateRedisClient()
        {
            string[] servers = FleetServiceClientHelper.CreateClient<SystemOptionProvider>().GetCacheServiceAddress(SystemParams.CompanyID);
            if ((servers == null) || (servers.Length == 0))
            {
                return null;
            }
            else
            {
                return new CacheClient("IRONINTEL_" + SystemParams.CompanyID.ToUpper(), servers);
            }
        }
    
        private static CacheClient Client
        {
            get
            {
                if (_Client == null)
                {
                    lock (_sycobj)
                    {
                        if (_Client == null)
                        {
                            _Client = CreateRedisClient();
                        }
                    }
                }
                return _Client;
            }
        }

        public static void Remove(string key)
        {
            if (Client != null)
            {
                try
                {
                    Client.Remove(key);
                }
                catch
                { }
            }
        }

        public static void SetValue(string key, byte[] buffer, TimeSpan expire)
        {
            if (buffer == null)
            {
                Remove(key);
            }
            else if (Client != null)
            {
                try
                {
                    Client.SetValue(key, buffer, expire);
                }
                catch
                { }
            }
        }

        public static byte[] GetValue(string key)
        {
            if (Client != null)
            {
                try
                {
                    return Client.GetValue(key);
                }
                catch
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }
    }
}