using System;
using System.IO;
using System.Threading;
using GxPress.Service.Interface.Video;
using Microsoft.Extensions.Caching.Distributed;

namespace GxPress.Service.Implement.Video
{
    public class VideoService : IVideoService
    {
        private readonly IDistributedCache _cache;
        public VideoService(IDistributedCache cache)
        {
            _cache = cache;
        }
        /// <summary>
        /// 工作线程
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="bytsize"></param>
        /// <param name="blength"></param>
        /// <param name="videoName"></param>
        public void RedisVideo(string filepath, byte[] bytsize, int blength, string videoName)
        {
            //创建后台工作线程
            Thread t2 = new Thread(new ParameterizedThreadStart(RedisSendAsync));
            t2.IsBackground = true;//设置为后台线程
            var redisVideoModel = new RedisVideoParameter
            {
                ByteLength = blength,
                FilePath = filepath,
                ByteSize = bytsize,
                VideoName = videoName
            };
            t2.Start(redisVideoModel);
        }
        public void RedisSendAsync(object data)
        {
            //转换
            var redisVideoModel = data as RedisVideoParameter;
            var byteSize = new byte[redisVideoModel.ByteLength];
            //获取文件流
            using (FileStream stream = new FileStream(redisVideoModel.FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                int i = 1;
                while (true)
                {
                    var cacheKey = redisVideoModel.VideoName + i;
                    var result = _cache.Get(cacheKey);
                    int r = stream.Read(redisVideoModel.ByteSize, 0, redisVideoModel.ByteLength);
                    //如果读取到的字节数为0，说明已到达文件结尾，则退出while循
                    if (r == 0)
                        break;
                    if (result == null)
                    {
                        _cache.Set(cacheKey, redisVideoModel.ByteSize, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(6000) });
                    }
                    //初始化
                    redisVideoModel.ByteSize = new byte[redisVideoModel.ByteLength];
                    i++;
                }
                stream.Close();
            }
        }
    }

    public class RedisVideoParameter
    {
        public string FilePath { get; set; }
        public byte[] ByteSize { get; set; }
        public int ByteLength { get; set; }
        public string VideoName { get; set; }
    }
}