using System;
using System.Threading;
using System.IO;
using Aliyun.OSS;
using Library;
using System.Text.RegularExpressions;

namespace MySystem
{   
    public class OssHelper
    {
        public readonly static OssHelper Instance = new OssHelper();
        private OssHelper()
        {
        }

        public void Start()//启动
        {
            Thread thread = new Thread(threadStart);
            thread.IsBackground = true;
            thread.Start();
        }

        public void Add(string data)
        {
            function.WritePage("/OSSTempFiles/", function.MD532(Guid.NewGuid().ToString()) + ".txt", data);
        }

        private void threadStart()
        {
            var client = new OssClient(AppConfig.Oss.endpoint, AppConfig.Oss.key, AppConfig.Oss.secret);
            while (true)
            {
                string dataFilePath = function.getPath("/OSSTempFiles/");
                DirectoryInfo TheFolder = new DirectoryInfo(dataFilePath);
                if (TheFolder.Exists)
                {
                    //遍历文件
                    if (TheFolder.GetFiles().Length > 0)
                    {
                        try
                        {
                            foreach (FileInfo NextFile in TheFolder.GetFiles())
                            {
                                string FileFullName = dataFilePath + NextFile.Name;
                                string data = function.ReadInstance("/OSSTempFiles/" + NextFile.Name);
                                ScanQueue(data, FileFullName, client);
                            }
                        }
                        catch (Exception ex)
                        {
                            function.WriteLog(ex.ToString(), "OSS上传队列异常");
                        }
                    }
                }
                //没有任务，休息1秒钟
                Thread.Sleep(1000);
            }
        }

        //要执行的方法
        public void ScanQueue(string data, string FileFullName)
        {
            var client = new OssClient(AppConfig.Oss.endpoint, AppConfig.Oss.key, AppConfig.Oss.secret);
            ScanQueue(data, FileFullName, client);
        }
        private void ScanQueue(string data, string FileFullName, OssClient client)
        {
            // 上传文件。
            string localFile = function.getPath(data);
            string filePath = data.TrimStart('/');
            if (!data.StartsWith(AppConfig.Oss.PathName))
            {
                filePath = AppConfig.Oss.PathName + data;
            }
            var result = client.PutObject(AppConfig.Oss.bucketName, filePath, localFile, new ObjectMetadata()
            {
                ExpirationTime = DateTime.Parse("2050-12-31 23:59:59")
            });
            if (!string.IsNullOrEmpty(result.ETag))
            {
                if (result.ETag.Length == 32)
                {
                    if (File.Exists(localFile))
                    {
                        File.Delete(localFile);
                    }
                }
            }

            if (File.Exists(FileFullName))
            {
                File.Delete(FileFullName);
            }
        }




        /// <summary>
        /// 解析编辑器中的图片(oss)
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public string CheckOSSPic(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                content = "";
            }
            if (AppConfig.Oss.OssStatus)
            {
                MatchCollection MC = Regex.Matches(content, "<img.*?>");
                foreach (Match match in MC)
                {
                    string imgstr = match.Value;
                    Match submatch = Regex.Match(imgstr, "src=\".*?\"");
                    if (submatch.Success)
                    {
                        string src = submatch.Value.Replace("src=\"", "").Replace("\"", "");
                        if (!src.StartsWith("http"))
                        {
                            content = content.Replace(src, AppConfig.Oss.SourceHost + src);
                        }
                    }
                }
            }
            return content;
        }
    }
}