using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using TABS.MailCarrier.WebSDK;
using TABS.MailCarrier.WebSDK.Board;

/// <summary>
/// 게시판 지원 유틸리티
/// </summary>
public class BoardUtil
{
    public BoardUtil()
    {
    }

    /// <summary>
    /// img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEU 와 같은 인라인 이미지 태그를 메일 인라인 이미지로 변환한다.
    /// </summary>
    /// <param name="html"></param>
    /// <param name="message"></param>
    /// <returns></returns>
    public static string ConvertBinaryImgTagToImgTag(string html, List<Attachment> attachments)
    {
        string[] ext = { "png", "jpeg", "gif", "bmp", "" };
        try
        {
            for (int i = 0; ext[i].Length > 0; i++)
            {
                string pattern = string.Format(@"src=""data:image/{0};base64,(.*?)""", ext[i]);
                Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
                Match m = r.Match(html);
                while (m.Success)
                {
                    Guid fileId = Guid.NewGuid();
                    string base64 = m.Groups[1].Value;
                    string imgName = string.Format("{0:N}.{1}", fileId, ext[i]);
                    byte[] imgData = System.Convert.FromBase64String(base64);
                    string imgPath = string.Format("{0}\\{1}", GlobalConfig.WebShareTempPath, imgName);
                    using (FileStream fs = new FileStream(imgPath, FileMode.Create, FileAccess.Write))
                    {
                        fs.Write(imgData, 0, imgData.Length);
                        fs.Close();

                        Attachment attachment = new Attachment(fileId, imgName, imgPath);
                        attachments.Add(attachment);

                        string imgTag = string.Format("src=\"ViewInlineFile.ashx?id={0}\"", attachment.ID);
                        html = html.Remove(m.Index, m.Length).Insert(m.Index, imgTag);
                    }
                    m = r.Match(html);
                }
            }
        }
        catch
        {
        }
        return html;
    }
}