using Azure.Storage.Files.Shares;
using Azure.Storage.Files.Shares.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
//using System.Runtime.Caching;
using Microsoft.Extensions.Caching.Memory;

namespace PhotoTkutimes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ImgFileController : ControllerBase
    {
        public MemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions());
        private readonly IConfiguration _configuration;
        public ImgFileController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        public MemoryStream DownloadFromFileStorage(ArrayList dirArray, string fn)
        {
            MemoryStream ms = new MemoryStream();
            try
            {
                string connectionString = _configuration.GetValue<string>("ShareString");
                string shareName = _configuration.GetValue<string>("ShareName");
                ShareClient share = new ShareClient(connectionString, shareName);
                ShareDirectoryClient directory = share.GetRootDirectoryClient();
                foreach (string s in dirArray)
                {
                    if (s == "f")
                    {
                        directory = directory.GetSubdirectoryClient("m");
                    }
                    else
                    {
                        directory = directory.GetSubdirectoryClient(s);
                    }

                }
                // Get a reference to a subdirectory not located on root level

                //directory = directory.GetSubdirectoryClient("0000");
                //directory = directory.GetSubdirectoryClient("m");
                ShareFileClient file = directory.GetFileClient(fn);
                ShareFileDownloadInfo download = file.Download();
                download.Content.CopyTo(ms);
            }
            catch (Exception e)
            {
                e.ToString();
            }
            return ms;
        }
        [HttpGet]
        public string Show()
        {
            return "hello";
        }
        [HttpGet("{fn}")]
        public IActionResult Get(string fn)
        {

            string filename;
            MemoryStream ms = new MemoryStream();
            Models.Security security = new Models.Security();
            char[] splitter_securityIDs = { '/' };
            ArrayList dirArray = new ArrayList();
            dirArray.Add("san_tkutimes");

            try
            {
                filename = security.Decrypt(fn);
                dirArray.AddRange(filename.Split(splitter_securityIDs));
                if (dirArray.Count > 1)
                {
                    dirArray.RemoveAt(dirArray.Count - 1);
                }
                filename = Path.GetFileName(filename);
            }
            catch (Exception e)
            {
                filename = e.ToString();
            }
            //ArrayList dirArray = new ArrayList();
            //dirArray.Add("san_tkutimes");
            //dirArray.Add("Photos");
            //dirArray.Add("0000");
            //dirArray.Add("m");
            //fn = "31e078f3-6b99-4b7d-8177-846e75b6df5a.jpg";


            if (string.IsNullOrEmpty(filename))
            {
                return NotFound();
            }
            try
            {

                if (!memoryCache.TryGetValue(fn, out ms))
                {
                    //string watermaskString = "淡江時報社";
                    var memoryStream = DownloadFromFileStorage(dirArray, filename);
                    //memoryStream.Seek(0, SeekOrigin.Begin);
                    //using (var bitmap = Bitmap.FromStream(memoryStream))
                    //{
                    //    ms = new MemoryStream();
                    //    using (var tempBitmap = new Bitmap(bitmap.Width, bitmap.Height))
                    //    {
                    //        using (Graphics grp = Graphics.FromImage(tempBitmap))
                    //        {

                    //            grp.DrawImage(bitmap, 0, 0);
                    //            bitmap.Dispose();
                    //            tempBitmap.Save(ms, ImageFormat.Jpeg);
                    var cacheEntryOptions = new MemoryCacheEntryOptions()
                        .SetSlidingExpiration(TimeSpan.FromHours(1))
                        .SetSize(2048);
                    memoryCache.Set(fn, ms, cacheEntryOptions);
                    ms = memoryStream;
                    //        }
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {

            }
            ms.Seek(0, SeekOrigin.Begin);

            // 回傳檔案到 Client 需要附上 Content Type，否則瀏覽器會解析失敗。
            return new FileStreamResult(ms, "image/jpeg");
        }
    }
}
