using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;
using TABS.MailCarrier.WebSDK.Mail;

/// <summary>
/// 새 메일 부분에서 사용되는 유틸리티 메서드 제공
/// </summary>
public class NewMsgUtil
{
    public enum MsgType
    {
        To = 0,
        Cc = 1,
        Bcc = 2
    }

    public enum MsgSource
    {
        Email = 0,
        Contact = 1,
        Orgz = 2
    }

    public NewMsgUtil()
    {
    }

    public static string GetMsgType(NewMsgUtil.MsgType type)
    {
        if (type == MsgType.To) return "to";
        else if (type == MsgType.Cc) return "cc";
        else if (type == MsgType.Bcc) return "bcc";
        else return "";
    }

    public static string GetMsgSource(NewMsgUtil.MsgSource source)
    {
        if (source == MsgSource.Email) return "email";
        else if (source == MsgSource.Contact) return "contact";
        else if (source == MsgSource.Orgz) return "orgz";
        else return "";
    }

    /// <summary>
    /// 문자열로 부터 Email, Contact, Orgz 정보를 반환한다.
    /// </summary>
    /// <param name="addrs"></param>
    /// <param name="type"></param>
    /// <param name="source"></param>
    /// <returns></returns>
    public static List<RcptItem> GetRecipientByType(string addrs, NewMsgUtil.MsgType type, NewMsgUtil.MsgSource source)
    {
        if (source == MsgSource.Email)
        {
            return GetRecipientByEmail(addrs, type);
        }
        else if (source == MsgSource.Contact)
        {
            return GetRecipientByContact(addrs, type);
        }
        else if (source == MsgSource.Orgz)
        {
            return GetRecipientByOrgz(addrs, type);
        }
        return null;
    }

    /// <summary>
    /// 회신, 전체회신, 전달시 Body에 포함되는 Header정보를 반환한다.
    /// </summary>
    /// <param name="message"></param>
    /// <returns></returns>
    public static string GetFormattedMessageHeader(Message message)
    {
        StringBuilder sb = new StringBuilder(1024);
        sb.Append("\r\n<-----Original Message----->\r\n\r\n");
        if (message.Sender.Address != "" && message.Sender.Address != message.FromAddress)
        {
            string senderName = message.Sender.Name.Trim();
            if (senderName != "")
                sb.Append(string.Format("> From: \"{0}\" <{1}> On Behalf Of {2}\r\n", senderName, message.Sender.Address, message.FromAddress));
            else
                sb.Append(string.Format("> From: {0} On Behalf Of {1}\r\n", message.Sender.Address, message.FromAddress));
        }
        else
        {
            sb.Append(string.Format("> From: \"{0}\" <{1}>\r\n", message.FromName.Trim(), message.FromAddress));
        }

        IFormatProvider culture = new System.Globalization.CultureInfo("en-US", true);
        string[] sentTime = WebUser.CurrentUser.ToLocalTime(message.SentTime).GetDateTimeFormats('F', culture);        
        sb.Append("> To:");
        for (int i = 0; i < message.To.Length; i++)
        {
            Recipient recipient = message.To[i];
            if (recipient.Name != "" && recipient.Address != "")
                sb.Append(string.Format(@"""{0}"" <{1}>", recipient.Name, recipient.Address));
            else if (recipient.Name != "")
                sb.Append(string.Format(@"""{0}""", recipient.Name));
            else if (recipient.Address != "")
                sb.Append(string.Format(@"""{0}""", recipient.Address));
            if (i != message.To.Length - 1) sb.Append("; ");
        }
        sb.Append("\r\n");        
        if (message.Cc.Length > 0)
        {
            sb.Append("> Cc:");
            for (int i = 0; i < message.Cc.Length; i++)
            {
                Recipient recipient = message.Cc[i];
                if (recipient.Name != "" && recipient.Address != "")
                    sb.Append(string.Format(@"""{0}"" <{1}>", recipient.Name, recipient.Address));
                else if (recipient.Name != "")
                    sb.Append(string.Format(@"""{0}""", recipient.Name));
                else if (recipient.Address != "")
                    sb.Append(string.Format(@"""{0}""", recipient.Address));
                if (i != message.Cc.Length - 1) sb.Append("; ");
            }
            sb.Append("\r\n");
        }
        sb.Append(string.Format("> Sent: {0}\r\n", sentTime));
        sb.Append(string.Format("> Subject:{0}", message.Subject));
        sb.Append("\r\n");

        return sb.ToString();
    }

    /// <summary>
    /// 회신, 전체회신, 전달시 Body에 포함되는 Header정보를 반환한다.
    /// </summary>
    /// <param name="message"></param>
    /// <returns></returns>
    public static string GetFormattedMessageHeaderHtml(Message message)
    {
        StringBuilder sb = new StringBuilder(1024);
        sb.Append("<p>&nbsp;</p><hr tabIndex=-1 />");
        if (message.Sender.Address != "" && message.Sender.Address != message.FromAddress)
        {
            string senderName = message.Sender.Name.Trim();
            if (senderName != "")
                sb.Append(string.Format("<div><b>From: </b> \"{0}\" &lt;{1}&gt; <b>On Behalf Of</b> {2}</div>", senderName, message.Sender.Address, message.FromAddress));
            else
                sb.Append(string.Format("<div><b>From: </b> {0} <b>On Behalf Of</b> {1}</div>", message.Sender.Address, message.FromAddress));
        }
        else
        {
            string fromName = message.FromName.Trim();
            if (fromName.Length > 0)
                sb.Append(string.Format("<div><b>From: </b> \"{0}\" &lt;{1}&gt;</div>", fromName, message.FromAddress));
            else
                sb.Append(string.Format("<div><b>From: </b> &lt;{0}&gt;</div>", message.FromAddress));
        }
        IFormatProvider culture = new System.Globalization.CultureInfo("en-US", true);
        string[] sentTime = WebUser.CurrentUser.ToLocalTime(message.SentTime).GetDateTimeFormats('F', culture);
        sb.Append(string.Format("<div><b>Sent:</b> {0}</div>", sentTime));
        sb.Append("<div><b>To: </b>");
        for (int i = 0; i < message.To.Length; i++)
        {
            Recipient recipient = message.To[i];
            if (recipient.Name != "" && recipient.Address != "")
                sb.Append(string.Format(@"""{0}"" &lt;{1}&gt;", recipient.Name, recipient.Address));
            else if (recipient.Name != "")
                sb.Append(string.Format(@"""{0}""", recipient.Name));
            else if (recipient.Address != "")
                sb.Append(string.Format(@"{0}", recipient.Address));
            if (i != message.To.Length - 1) sb.Append("; ");
        }

        sb.Append("</div>");
        if (message.Cc.Length > 0)
        {
            sb.Append("<div><b>Cc: </b>");
            for (int i = 0; i < message.Cc.Length; i++)
            {
                Recipient recipient = message.Cc[i];
                if (recipient.Name != "" && recipient.Address != "")
                    sb.Append(string.Format(@"""{0}"" &lt;{1}&gt;", recipient.Name, recipient.Address));
                else if (recipient.Name != "")
                    sb.Append(string.Format(@"""{0}""", recipient.Name));
                else if (recipient.Address != "")
                    sb.Append(string.Format(@"{0}", recipient.Address));
                if (i != message.Cc.Length - 1) sb.Append("; ");
            }
            sb.Append("</div>");
        }
        sb.Append(string.Format("<div><b>Subject:</b>{0}</div>", message.Subject));
        sb.Append("<p>&nbsp;</p>");

        return sb.ToString();
    }

    private static List<RcptItem> GetRecipientByEmail(string addrs, MsgType type)
    {
        List<RcptItem> items = new List<RcptItem>();
        Regex r = new Regex(MailUtil.EmailPatternWithName, RegexOptions.IgnoreCase);
        Match m = r.Match(addrs);
        while (m.Success)
        {
            string name = m.Groups[1].ToString();
            string address = m.Groups[3].ToString();
            name = name.Replace("\"", "");
            items.Add(new RcptItem(GetMsgType(type), name, address, GetMsgSource(MsgSource.Email)));
            m = m.NextMatch();
        }
        return items;
    }

    private static List<RcptItem> GetRecipientByContact(string addrs, MsgType type)
    {
        List<RcptItem> items = new List<RcptItem>();
        string pattern = @"@\x5b([^\x5d]+)\x5d\x28([^\x29]+)\x29";
        Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
        Match m = r.Match(addrs);
        while (m.Success)
        {
            string name = m.Groups[1].ToString();
            string uid = m.Groups[2].ToString();
            items.Add(new RcptItem(GetMsgType(type), name, uid, GetMsgSource(MsgSource.Contact)));
            m = m.NextMatch();
        }
        return items;
    }

    private static List<RcptItem> GetRecipientByOrgz(string addrs, MsgType type)
    {
        List<RcptItem> items = new List<RcptItem>();
        string pattern = @"#\x5b([^\x5d]+)\x5d\x28([^\x29]+)\x29";
        Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
        Match m = r.Match(addrs);
        while (m.Success)
        {
            string name = m.Groups[1].ToString();
            string uid = m.Groups[2].ToString();
            items.Add(new RcptItem(GetMsgType(type), name, uid, GetMsgSource(MsgSource.Orgz)));
            m = m.NextMatch();
        }
        return items;
    }
}
