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;
using System.Drawing.Drawing2D;
using System.IO;
using PhotoTkutimes.Models;
using Microsoft.AspNetCore.DataProtection.KeyManagement;

namespace PhotoTkutimes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class JpgPathController : ControllerBase
    {
        public MemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions());
        private readonly IConfiguration _configuration;
        public JpgPathController(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 "hellojpg";
        }
        [HttpGet("{fn}")]
        public IActionResult Get(string fn)
        {

            string filename;
            string photopath = "";
            MemoryStream ms = new MemoryStream();

            char[] splitter_securityIDs = { '/' };
            ArrayList dirArray = new ArrayList();
            dirArray.Add("san_tkutimes");

            try
            {


                filename = fn.Replace("_","/");
                
                photopath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", filename);
                try
                {
                    if (!Directory.Exists(Path.GetDirectoryName(photopath)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(photopath));
                    }
                }
                catch { }
                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();
            }

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



                if (!memoryCache.TryGetValue(fn, out ms))
                {

                    if (System.IO.File.Exists(photopath))
                    {
                        ms = new MemoryStream(System.IO.File.ReadAllBytes(photopath));
                        ms.Seek(0, SeekOrigin.Begin);
                    }
                    else
                    {

                        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))
                                {
                                    int alpha = 100;
                                    grp.DrawImage(bitmap, 0, 0);
                                    bitmap.Dispose();
                                    if (tempBitmap.Width >= 600)
                                    {
                                        Brush brush = new SolidBrush(Color.FromArgb(alpha, 120, 0, 0));
                                        Font font = new System.Drawing.Font("Segoe UI", 32, FontStyle.Bold, GraphicsUnit.Pixel);
                                        SizeF textSize = grp.MeasureString(watermaskString, font);
                                        Point position = new Point((tempBitmap.Width - ((int)textSize.Width + 10)),
                                            (tempBitmap.Height - ((int)textSize.Height + 10)));
                                        grp.DrawString(watermaskString, font, brush, position);

                                        brush = new SolidBrush(Color.FromArgb(alpha, 200, 200, 200));
                                        //font = new System.Drawing.Font("Segoe UI", 30, FontStyle.Bold, GraphicsUnit.Pixel);
                                        //textSize = grp.MeasureString(watermaskString, font);
                                        position = new Point((tempBitmap.Width - ((int)textSize.Width + 15)),
                                           (tempBitmap.Height - ((int)textSize.Height + 13)));
                                        grp.DrawString(watermaskString, font, brush, position);

                                    }
                                    else if (tempBitmap.Height >= 600)
                                    {
                                        Brush brush = new SolidBrush(Color.FromArgb(alpha, 120, 0, 0));
                                        Font font = new System.Drawing.Font("Segoe UI", 48, FontStyle.Bold, GraphicsUnit.Pixel);
                                        SizeF textSize = grp.MeasureString(watermaskString, font);
                                        Point position = new Point((tempBitmap.Width - ((int)textSize.Width + 10)),
                                            (tempBitmap.Height - ((int)textSize.Height + 10)));
                                        //Point position = new Point(tempBitmap.Width, tempBitmap.Height - (int) textSize.Width);
                                        //Matrix mtxSave = grp.Transform;

                                        //Matrix mtxRotate = grp.Transform;
                                        //mtxRotate.RotateAt(-15, position);
                                        //grp.Transform = mtxRotate;
                                        grp.DrawString(watermaskString, font, brush, position);

                                        brush = new SolidBrush(Color.FromArgb(alpha, 200, 200, 200));
                                        //font = new System.Drawing.Font("Segoe UI", 30, FontStyle.Bold, GraphicsUnit.Pixel);
                                        //textSize = grp.MeasureString(watermaskString, font);
                                        position = new Point((tempBitmap.Width - ((int)textSize.Width + 13)),
                                           (tempBitmap.Height - ((int)textSize.Height + 12)));
                                        grp.DrawString(watermaskString, font, brush, position);

                                    }
                                    tempBitmap.Save(ms, ImageFormat.Jpeg);
                                    var cacheEntryOptions = new MemoryCacheEntryOptions()
                                        .SetSlidingExpiration(TimeSpan.FromHours(1))
                                        .SetSize(2048);
                                    memoryCache.Set(fn, ms, cacheEntryOptions);

                                    using (FileStream file = new FileStream(photopath, FileMode.Create, System.IO.FileAccess.Write))
                                    {
                                        MemoryStream msOutput = new MemoryStream(ms.ToArray());
                                        ms.CopyTo(msOutput);
                                        byte[] bytes = new byte[msOutput.Length];
                                        msOutput.Read(bytes, 0, (int)msOutput.Length);
                                        file.Write(bytes, 0, bytes.Length);
                                        msOutput.Close();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
            ms.Seek(0, SeekOrigin.Begin);

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