using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TABS.MailCarrier.AuxLib;
using TABS.MailCarrier.WebSDK;
using TABS.MailCarrier.WebSDK.Mail;

public partial class Mail_ViewEml : System.Web.UI.Page
{
    private const int MAX_RECIPIENTS = 10;      // 최대 수신자 출력 수

    protected string _ccCssClass = "";          // 참조 영역 class 값
    protected string _attachCssClass = "";      // 첨부 영역 class 값

    protected override void InitializeCulture()
    {
        string defLang = WebUser.CurrentUser.UiLanguage;
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(defLang);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(defLang);
        base.InitializeCulture();
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        WebUtil.SetMcCommonCss(Page.Header);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Page.Title = AppSetting.GetTitleInfo(Request).Title;

            string msgFile = WebParam.GetStrParamValue("msgfile");
            LoadMailMessage(msgFile, "auto");
        }
    }

    private void LoadMailMessage(string msgFile, string charset)
    {
        string emlPath = string.Format("{0}\\{1}", GlobalConfig.WebShareTempPath, msgFile);
        Message message = new Message(emlPath);
        try
        {
            message.Charset = charset;
            message.Load();
            ShowMailMessage(message);
        }
        catch (LoadFailException)
        {
        }
    }

    /// <summary>
    /// 메일 메시지를 출력한다.
    /// </summary>
    /// <param name="message"></param>
    private void ShowMailMessage(Message message)
    {
        // 제목 출력
        SubjectLabel.Text = message.Subject;

        // 보낸 사람 출력
        FromAddrLabel.Text = MailUtil.GetMailFromString4Html(message.FromName, message.FromAddress);

        // 받는 사람 출력
        ToAddrTag.Text = MailUtil.GetRecipientsString4Html(message.To, MAX_RECIPIENTS);

        // 참조 출력
        CcAddrTag.Text = MailUtil.GetRecipientsString4Html(message.Cc, MAX_RECIPIENTS);
        _ccCssClass = (CcAddrTag.Text.Length == 0) ? "collapse" : "";

        // 받은 날짜 출력 - Date 부분이 잘못 구성된 메시지가 있으므로 예외를 처리한다.
        try
        {
            RecvDateLabel.Text = string.Format("{0:f}", WebUser.CurrentUser.ToLocalTime(message.SentTime));
        }
        catch
        {
            RecvDateLabel.Text = message.GetHeader("Date");
        }

        // 첨부 파일 출력
        int attachCount = 0, attachSize = 0;
        bool relatedAttach = false;
        if (message.Attachments.Length > 0)
        {
            ExtIconMap extIconMap = new ExtIconMap();
            StringBuilder attchSb = new StringBuilder();
            foreach (Attachment attach in message.Attachments)
            {
                if (attach.ContentType == "message/rfc822")
                {
                    string item = (!attach.Deleted) ?
                        string.Format("<a href='#' class='list-group-item' onclick='OpenViewEmlWindow(\"{1}\")'><img src='../Images/Ext/{0}'/>{2} ({3})</a>",
                            extIconMap.GetIconName(attach.FilePath), Server.UrlEncode(attach.FilePath), attach.FileName, WebUtil.GetFormattedFileSize(attach.Size)) :
                        string.Format("<div class='list-group-item'><img src='../Images/Ext/{0}'/><del>{1} ({2})</del></div>",
                            extIconMap.GetIconName(attach.FilePath), attach.FileName, WebUtil.GetFormattedFileSize(attach.Size));

                    attchSb.Append(item);
                    attachCount++;
                    attachSize += attach.Size;
                }
                else if (attach.ContentID != "" && message.HtmlBody.IndexOf(attach.ContentID) > 0)
                {
                    relatedAttach = true;
                }
                else
                {
                    // 잘못 구성된 인라인 파일이더라도 ContentID만 존재하면 HTML 구성시 인라인이 처리될 수 있도록 relatedAttach = true로 지정한다.
                    //  - ContentID가 존재하고 attachment로 명시되어 있지만 실제는 inline으로 사용되는 메시지가 있다.
                    if (attach.ContentID != "") relatedAttach = true;

                    string item = (!attach.Deleted) ?
                        string.Format("<a href='Download.ashx?file={1}&name={2}' class='list-group-item'><img src='../Images/Ext/{0}'/>{3} ({4})</a>",
                            extIconMap.GetIconName(attach.FilePath), attach.FilePath, Server.UrlEncode(attach.FileName), attach.FileName, WebUtil.GetFormattedFileSize(attach.Size)) :
                        string.Format("<div class='list-group-item'><img src='../Images/Ext/{0}'/><del>{1} ({2})</del></div>",
                            extIconMap.GetIconName(attach.FilePath), attach.FileName, WebUtil.GetFormattedFileSize(attach.Size));
                    attchSb.Append(item);
                    attachCount++;
                    attachSize += attach.Size;
                }
            }
            AttachListTag.Text = attchSb.ToString();
        }
        _attachCssClass = (attachCount > 0) ? "collapse in" : "collapse";
        AttachSummaryLabel.Text = string.Format(GetLocalResourceObject("AttachSummary").ToString(), attachCount, WebUtil.GetFormattedFileSize((long)attachSize));

        // 본문 출력
        if (message.HtmlBody != "")
        {
            // <body>에 있는 스타일 등을 제거하기 위해 <body></body>를 제거한다.
            HtmlStripper htmlStripper = new HtmlStripper();
            string html = htmlStripper.StripBodyTag(message.HtmlBody, true);

            if (relatedAttach)
            {
                Array.Sort<Attachment>(message.Attachments, new Comparison<Attachment>((i1, i2) => i2.ContentID.CompareTo(i1.ContentID)));
                foreach (Attachment attach in message.Attachments)
                {
                    if (attach.ContentID != "")
                    {
                        string cid = "cid:" + attach.ContentID;
                        string downlink = "Download.ashx?content=" + attach.FilePath;
                        html = html.Replace(cid, downlink);
                    }
                }
            }
            MsgBodyHolder.Controls.Add(new LiteralControl(html));
        }
        else
        {
            string html = WebUtil.GetFormattedPlainText(message.TextBody, true);
            MsgBodyHolder.Controls.Add(new LiteralControl(html));
        }
    }
}