using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace Siger.Middlelayer.Redis.Repositories
{
    public class FileSystemRepository : RedisRepositoryBase, IDisposable
    {
        public const string FileRedisKey = "RedisFile_FileSystemState";
        public const string FileIdRedisKey = "RedisFile_FileIdInfo";
        public const string FileIdRedisChunkStatistics = "RedisFile_AssignFileStatistic";
        public const string FileIdRedisChunkCache = "RedisFile_FileIdChunckCache";

        public FileSystemRepository() : base(0, 0)
        {

        }
        public FileSystemRepository(int companyId, int projectId) : base(companyId, projectId)
        {

        }


        public T GetFileInfo<T>(string key, string code)
        {
            var item = Client.HGet(key, code);
            if (item == null)
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject<T>(item);
        }

        public bool SetFileInfo<T>(string key, string code, T item)
        {
            var itemVal = JsonConvert.SerializeObject(item);
            return Client.HSet(key, code, itemVal);
        }

        public bool SetBaseType<T>(string key, string code, T item)
        {
            return Client.HSet(key, code, (object)item);
        }

        public T GetBaseType<T>(string key, string code)
        {
            var item = Client.HGet(key, code);
            var obj = Convert.ChangeType(item, typeof(T));
            return (T)obj;
        }


        public long SetCacheInfo(string id, string item)
        {
            return Client.RPush(FileIdRedisChunkCache + "_" + id, item);
        }

        public string[] GetCacheInfo(string id)
        {
            return Client.LRange(FileIdRedisChunkCache + "_" + id, 0, -1);
        }

        public void Dispose()
        {
            Client?.Dispose();
        }
    }
}
