using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

public static class GlobalClass
{
    public static IServiceProvider ServiceProvider;
    public static bool isURL(string url)
    {
        return Uri.IsWellFormedUriString(url, UriKind.Absolute);
    }

    public static string GetIP(this HttpContext context)
    {

        var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
        if (string.IsNullOrEmpty(ip))
        {
            ip = context.Connection.RemoteIpAddress.ToString();
        }
        return ip;
    }

    public static string CreateRandomCode(int Number)
    {
        string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
        string[] allCharArray = allChar.Split(',');
        string randomCode = "";

        Random rand = new Random(Guid.NewGuid().GetHashCode());
        for (int i = 0; i <= Number - 1; i++)
        {
            int t = rand.Next(allCharArray.Length);
            randomCode += allCharArray[t];
        }
        return randomCode;
    }

    public static string CreateUniRandomCode(int Number)
    {
        string allChar = "2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,U,V,W,X,Y,Z";
        string[] allCharArray = allChar.Split(',');
        string randomCode = "";

        Random rand = new Random(Guid.NewGuid().GetHashCode());
        for (int i = 0; i <= Number - 1; i++)
        {
            int t = rand.Next(allCharArray.Length);
            randomCode += allCharArray[t];
        }
        return randomCode;
    }

    public static string ToMD5(this string str)
    {
        using (var cryptoMD5 = System.Security.Cryptography.MD5.Create())
        {
            //將字串編碼成 UTF8 位元組陣列
            var bytes = Encoding.UTF8.GetBytes(str);

            //取得雜湊值位元組陣列
            var hash = cryptoMD5.ComputeHash(bytes);

            //取得 MD5
            var md5 = BitConverter.ToString(hash)
              .Replace("-", String.Empty)
              .ToLower();

            return md5;
        }
    }

    public static string Sha256(this string input)
    {
        System.Security.Cryptography.SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider();
        Byte[] ByteString = Encoding.ASCII.GetBytes(input);
        ByteString = sha256.ComputeHash(ByteString);
        string returnString = "";
        foreach (Byte bt in ByteString)
        {
            returnString += bt.ToString("x2");
        }
        return returnString.ToLower();
    }
    /// <summary>
    /// Creates a SHA256 hash of the specified input.
    /// </summary>
    /// <param name="input">The input.</param>
    /// <returns>A hash.</returns>
    public static byte[] Sha256(this byte[] input)
    {
        if (input == null)
        {
            return null;
        }
        using (var sha = SHA256.Create())
        {
            return sha.ComputeHash(input);
        }
    }

    public static bool isEmail(string email)
    {
        //Email檢查格式
        System.Text.RegularExpressions.Regex EmailExpression = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", RegexOptions.Compiled | RegexOptions.Singleline);
        try
        {
            if (string.IsNullOrEmpty(email))
            {
                return false;
            }
            else
            {
                return EmailExpression.IsMatch(email);
            }
        }
        catch (Exception ex)
        {
            //log.Error(ex.Message);
            return false;
        }
    }

    public static string appsettings(string key)
    {
        var builder = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json");
        var config = builder.Build();
        return config[key];
    }

    public static Image embedImage(Image watermark, Image targetImg, int x, int y)
    {
        Image outImg;

        using (Graphics g = Graphics.FromImage(targetImg))
        {
            g.DrawImage(watermark, new Rectangle(x, y, watermark.Width, watermark.Height));
            outImg = (Image)targetImg.Clone();
        }

        return outImg;
    }

    public static Image resizeImage(Image image, int width, int height)
    {
        var destinationRect = new Rectangle(0, 0, width, height);
        var destinationImage = new Bitmap(width, height);

        destinationImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

        using (var graphics = Graphics.FromImage(destinationImage))
        {
            graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.CompositingQuality = CompositingQuality.HighQuality;

            using (var wrapMode = new ImageAttributes())
            {
                wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                graphics.DrawImage(image, destinationRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
            }
        }

        return (Image)destinationImage;
    }

    /// <summary>
    /// base 64字串格式的圖片轉成Image物件
    /// </summary>
    /// <param name="base64String"></param>
    /// <returns></returns>
    public static Image Base64StringToImage(string base64String)
    {
        // Convert base 64 string to byte[]
        byte[] Buffer = Convert.FromBase64String(base64String);

        byte[] data = null;
        Image oImage = null;
        MemoryStream oMemoryStream = null;
        Bitmap oBitmap = null;
        //建立副本
        data = (byte[])Buffer.Clone();
        try
        {
            oMemoryStream = new MemoryStream(data);
            //設定資料流位置
            oMemoryStream.Position = 0;
            oImage = System.Drawing.Image.FromStream(oMemoryStream);
            //建立副本
            oBitmap = new Bitmap(oImage);
        }
        catch
        {
            throw;
        }
        finally
        {
            oMemoryStream.Close();
            oMemoryStream.Dispose();
            oMemoryStream = null;
        }
        //return oImage;
        return oBitmap;
    }

    public static string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            // Convert Image to byte[]
            image.Save(ms, format);
            byte[] imageBytes = ms.ToArray();

            // Convert byte[] to base 64 string
            string base64String = Convert.ToBase64String(imageBytes);
            return base64String;
        }
    }
}
