using Hotline.Caching.Interfaces;
using Hotline.Configurations;
using Hotline.Settings;
using Microsoft.Extensions.Options;
using System.Text;
using System.Text.RegularExpressions;
using XF.Domain.Dependency;

namespace Hotline.Application.Bulletin
{
    public class BulletinApplication : IBulletinApplication, IScopeDependency
    {
        private readonly IOptionsSnapshot<AppConfiguration> _appOptions;
        private readonly ISystemSettingCacheManager _systemSettingCacheManager;

        public BulletinApplication(IOptionsSnapshot<AppConfiguration> appOptions,
                 ISystemSettingCacheManager systemSettingCacheManager)
        {
            _appOptions = appOptions;
            _systemSettingCacheManager= systemSettingCacheManager; 
        }

        /// <summary>
        /// 处理通知公告图片附件路径
        /// </summary>
        /// <param name="sHtmlText"></param>
        /// <returns></returns>
        public string GetSiteUrls(string sHtmlText)
        {
            sHtmlText = sHtmlText.Replace("&lt;", "<").Replace("&gt;", ">");

            //临时内容
            System.Text.StringBuilder sb = new StringBuilder();
            sb.Append(sHtmlText);
            // 定义正则表达式用来匹配 img 标签
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
            // 搜索匹配的字符串
            MatchCollection matches = regImg.Matches(sHtmlText);

            // 定义正则表达式用来匹配 video 标签
            Regex regvideo = new Regex(@"<video\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
            // 搜索匹配的字符串
            MatchCollection matchesvideo = regvideo.Matches(sHtmlText);

            var strSiteUrl = _systemSettingCacheManager.GetSetting(SettingConstants.OldFilesUrls)?.SettingValue[0];
         
            // 取得匹配项列表 视频
            foreach (Match match in matchesvideo)
            {
                if (-1 == match.Groups["imgUrl"].Value.IndexOf("http"))
                {
                    sb.Replace(match.Groups["imgUrl"].Value, strSiteUrl + match.Groups["imgUrl"].Value);
                    sb.Replace(strSiteUrl + strSiteUrl + match.Groups["imgUrl"].Value, strSiteUrl + match.Groups["imgUrl"].Value);
                }
            }

            // 取得匹配项列表
            foreach (Match match in matches)
            {
                if (-1 == match.Groups["imgUrl"].Value.IndexOf("http"))
                {
                    sb.Replace(match.Groups["imgUrl"].Value, strSiteUrl + match.Groups["imgUrl"].Value);
                    sb.Replace(strSiteUrl + strSiteUrl + match.Groups["imgUrl"].Value, strSiteUrl + match.Groups["imgUrl"].Value);
                }
            }

            return sb.ToString();
        }
    }
}
