using System;
using System.IO;
using GxPress.Service.Interface.Video;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Net.Http.Headers;

namespace GxPress.Api.AppControllers
{
    /// <summary>
    /// 访问
    /// </summary>
    [Route("/api/app/video")]
    [ApiController]
    [Authorize]
    public class VideoController : ControllerBase
    {
        private readonly IWebHostEnvironment _environment;
        private readonly IDistributedCache _cache;
        private readonly IVideoService videoService;
        private IHttpContextAccessor _contextAccessor;
        private HttpContext _context { get { return _contextAccessor.HttpContext; } }

        public VideoController(IWebHostEnvironment environment, IDistributedCache cache, IVideoService videoService, IHttpContextAccessor contextAccessor)
        {
            _environment = environment;
            _cache = cache;
            this.videoService = videoService;
            _contextAccessor = contextAccessor;
        }
        // /// <summary>
        // /// 分页视频流
        // /// </summary>
        // /// <returns></returns>
        // [HttpGet]
        // [AllowAnonymous]
        // public IActionResult GetVideo(int page)
        // {
        //     try
        //     {
        //         var path = Common.Tools.StringUtils.GetWebRootPath(_environment.WebRootPath);
        //         var filepath = path + "/cache/20200428/1588144602647614.mp4";
        //         FileInfo fileInfo = new FileInfo(filepath);
        //         var key = $"15881446026476141.mp4{page}";
        //         var result = _cache.Get(key);
        //         if (result != null)
        //             return File(result, "application/octet-stream", fileInfo.Name);
        //         var blength = 1024 * 1024 * 1;
        //         byte[] bytsize = new byte[blength];
        //         //获取文件名后缀
        //         string extension = Path.GetExtension(filepath);
        //         //
        //         videoService.RedisVideo(filepath, bytsize, blength, "15881446026476141.mp4");
        //         //获取文件流
        //         using (FileStream stream = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
        //         {
        //             while (true)
        //             {
        //                 int r = stream.Read(bytsize, 0, blength);
        //                 //如果读取到的字节数为0，说明已到达文件结尾，则退出while循
        //                 break;
        //             }
        //             stream.Close();
        //         }
        //         //获取后缀名
        //         var ext = fileInfo.Extension;
        //         new FileExtensionContentTypeProvider().Mappings.TryGetValue(ext, out var contenttype);
        //         var actionResult = File(bytsize, contenttype ?? "application/octet-stream", fileInfo.Name);
        //         return actionResult;
        //     }
        //     catch (FileNotFoundException e)
        //     {
        //         throw new Common.Exceptions.BusinessException(e.Message);
        //     }
        //     catch (IOException e)
        //     {
        //         throw new Common.Exceptions.BusinessException(e.Message);
        //     }
        // }

        /// <summary>
        /// 分页视频流
        /// </summary>
        /// <returns></returns>
        [HttpHead]
        [AllowAnonymous]
        public IActionResult GetVideoInfo()
        {
            try
            {
                var path = Common.Tools.StringUtils.GetWebRootPath(_environment.WebRootPath);
                var filepath = path + "/cache/20200428/1588144602647614.mp4";
                FileInfo fileInfo = new FileInfo(filepath);
                byte[] bytsize = new byte[fileInfo.Length];
                var ext = fileInfo.Extension;
                new FileExtensionContentTypeProvider().Mappings.TryGetValue(ext, out var contenttype);
                var actionResult = File(bytsize, contenttype ?? "application/octet-stream", fileInfo.Name);
                return actionResult;
            }
            catch (FileNotFoundException e)
            {
                throw new Common.Exceptions.BusinessException(e.Message);
            }
            catch (IOException e)
            {
                throw new Common.Exceptions.BusinessException(e.Message);
            }
        }

        /// <summary>
        /// 分页视频流
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public IActionResult GetVideo()
        {
            var range = Request.Headers["Range"].ToString().Replace("bytes=", "");
            try
            {
                var path = Common.Tools.StringUtils.GetWebRootPath(_environment.WebRootPath);
                var filepath = path + "/cache/20200428/1588144602647614.mp4";
                //var filepath = "http://localhost:83/cache/20200428/1588144602647614.mp4";
                //从第3个到第12个字节，共10个字节。（0是第一个字节）
                var begin = int.Parse(range.Split('-')[0]);
                var end = int.Parse(range.Split('-')[1]);
                var byteLength = (end - begin)+1;
                var bytes = new byte[byteLength];
                //var fristBytes = new byte[1024];
                FileInfo fileInfo = new FileInfo(filepath);
                //获取后缀名
                var ext = fileInfo.Extension;
                new FileExtensionContentTypeProvider().Mappings.TryGetValue(ext, out var contenttype);
                //获取文件流
                StreamReader stream = new StreamReader(System.IO.File.OpenRead(filepath));
                //stream.BaseStream.Read(fristBytes, 0, 1024);
                stream.BaseStream.Seek(begin, SeekOrigin.Begin);
                stream.BaseStream.Read(bytes, 0, byteLength);
                stream.Close();
                //var newBytes = new byte[fristBytes.Length + bytes.Length];
                // fristBytes.CopyTo(newBytes, 0);
                // bytes.CopyTo(newBytes, fristBytes.Length);
                _context.Response.Headers.Add(HeaderNames.AcceptRanges, "bytes");
                _context.Response.Headers.Add(HeaderNames.ContentRange, $"bytes {Request.Headers["Range"].ToString()}/{fileInfo.Length}");
                _context.Response.StatusCode = 206;
                var actionResult = File(bytes, contenttype ?? "application/octet-stream", fileInfo.Name);
                return actionResult;
            }
            catch (Exception ex)
            {
                throw new Common.Exceptions.BusinessException($"{ex.Message}");
            }
        }

    }
}