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 System.Web.Services;
using TABS.MailCarrier.WebSDK;
using TABS.MailCarrier.WebSDK.Mail;

// 모바일 버전에서 수신 확인 기능은 제공하지 않는다.
public partial class Mail_ReadRecipients : System.Web.UI.Page
{
    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;
        }
    }

    protected void RrGroupGridView_PreRender(object sender, EventArgs e)
    {
        GridView gv = (GridView)sender;
        if ((gv.ShowHeader == true && gv.Rows.Count > 0) || (gv.ShowHeaderWhenEmpty == true))
        {
            gv.HeaderRow.TableSection = TableRowSection.TableHeader;
        }
        if (gv.ShowFooter == true && gv.Rows.Count > 0)
        {
            gv.FooterRow.TableSection = TableRowSection.TableFooter;
        }
    }

    protected void RefreshButton_Click(object sender, EventArgs e)
    {
        RrGroupGridView.DataBind();
    }

    #region Ajax

    [WebMethod]
    public static string GetRrGroupHtml(string mrgId)
    {
        string defLang = WebUser.CurrentUser.UiLanguage;
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(defLang);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(defLang);

        string fmt = "<div class='row rrdata'><div class='col-xs-8 topline'>{0}<br/>" + HttpContext.GetGlobalResourceObject("Mail", "RrReadTime").ToString() + ":{1}<br />" +
          HttpContext.GetGlobalResourceObject("Mail", "RrSentStatus").ToString() + ":{2}</div><div class='col-xs-4 text-right topline'><br/>{3}</div></div>";
        StringBuilder html = new StringBuilder();
        ReadRecipientGroup group = new ReadRecipientGroup(new Guid(mrgId));
        foreach (ReadRecipient r in group.GetReadRecipient())
        {
            string name = (r.Name != "") ? r.Name : r.Address;
            string date = (r.ReadTime.HasValue) ? WebUser.CurrentUser.ToLocalTime(r.ReadTime.Value).ToString("g") : "-";
            string status = GetSendStatusString(r.MsgSendStatus, r.ErrorCode, r.ErrorText);
            bool cancelable = r.MsgSendStatus == ReadRecipient.SendStatus.Sent && !r.Read && IsMyDomain(r.Address);
            string cancelScript = (cancelable) ?
                string.Format("<a href='#' onclick=\"CancelSentMessage(event, '{0}', '{1}', '{2}')\">{3}</a>", mrgId, r.ID, WebUtil.EncodeJsString2(r.Address), HttpContext.GetGlobalResourceObject("Mail", "RrCancelSent").ToString()) : "-";

            html.Append(string.Format(fmt, name, date, status, cancelScript));
        }
        return html.ToString();
    }

    [WebMethod]
    public static void CancelGroupSentMessage(string mrgId)
    {
        ReadRecipientGroup readRecipient = new ReadRecipientGroup(new Guid(mrgId));
        foreach (ReadRecipient recipient in readRecipient.GetReadRecipient())
        {
            ReadRecipient.CancelSent(recipient.ID);
        }
    }

    [WebMethod]
    public static void CancelScheduledMailing(string mrgId)
    {
        ReadRecipientGroup readRecipient = new ReadRecipientGroup(new Guid(mrgId));
        readRecipient.CancelScheduledMailing();
    }

    [WebMethod]
    public static void CancelSentMessage(string mrrId)
    {
        ReadRecipient.CancelSent(new Guid(mrrId));
    }

    private static string GetSendStatusString(ReadRecipient.SendStatus sendStatus, int errCode, string errText)
    {
        string status = "-";
        switch (sendStatus)
        {
            case ReadRecipient.SendStatus.Queued:
                status = Resources.Mail.RrSendStatusQueued;
                break;
            case ReadRecipient.SendStatus.Retry:
                status = Resources.Mail.RrSendStatusRetry;
                break;
            case ReadRecipient.SendStatus.Sent:
                status = Resources.Mail.RrSendStatusSentOK;
                break;
            case ReadRecipient.SendStatus.DnsError:
                status = string.Format(Resources.Mail.RrSendStatusDnsErr, errCode, errText);
                break;
            case ReadRecipient.SendStatus.NetworkError:
                status = string.Format(Resources.Mail.RrSendStatusNetErr, errCode, errText);
                break;
            case ReadRecipient.SendStatus.SmtpError:
                status = string.Format(Resources.Mail.RrSendStatusSmtpErr, errCode, errText);
                break;
            case ReadRecipient.SendStatus.Canceled:
                status = Resources.Mail.RrSendStatusCanceled;
                break;
            case ReadRecipient.SendStatus.CanceledScheduledMailing:
                status = Resources.Mail.RrSendStatusMailingCanceled;
                break;
            case ReadRecipient.SendStatus.NotPermited:
                status = Resources.Mail.RrSendStatusNotPermited;
                break;
            case ReadRecipient.SendStatus.WaitingForPermit:
                status = Resources.Mail.RrSendStatusWaitingForPermit;
                break;
            case ReadRecipient.SendStatus.PermitCancelled:
                status = Resources.Mail.RrSendStatusPermitCanceled;
                break;
        }
        return status;
    }

    #endregion

    #region RrGroupGridView Methods

    protected string GetToAddr(string name, string address)
    {
        if (name != "") return name;
        return address;
    }

    protected string GetToAddr(string name, string address, int recipientsCount)
    {
        if (recipientsCount == 1)
        {
            return Server.HtmlEncode(GetToAddr(name, address));
        }
        else
        {
            if (name != "") return string.Format(GetLocalResourceObject("ToFmt").ToString(), Server.HtmlEncode(name), recipientsCount - 1);
            return string.Format(GetLocalResourceObject("ToFmt").ToString(), address, recipientsCount - 1);
        }
    }

    protected string GetSubject(string subject)
    {
        if (subject == "") subject = GetLocalResourceObject("NoSubject").ToString();
        return Server.HtmlEncode(subject);
    }

    protected string GetSentTime(DateTime sentTime, int flag, DateTime reserveTime)
    {
        ReadRecipientGroup.RRGroupFlag rrFlag = (ReadRecipientGroup.RRGroupFlag)flag;
        if ((rrFlag & ReadRecipientGroup.RRGroupFlag.Reserved) > 0)
        {
            return string.Format("<img src='../Images/Mail/msg_reserve.gif' /> {0}", WebUser.CurrentUser.ToLocalTime(reserveTime).ToString("g"));
        }
        else if ((rrFlag & ReadRecipientGroup.RRGroupFlag.Canceled) > 0)
        {
            return string.Format("<img src='../Images/Mail/msg_reserve_cancel.gif' /> {0}", WebUser.CurrentUser.ToLocalTime(sentTime).ToString("g"));
        }
        else
        {
            return WebUser.CurrentUser.ToLocalTime(sentTime).ToString("g");
        }
    }

    protected string GetCancelSentMessage(Guid mrgId, int flag)
    {
        ReadRecipientGroup.RRGroupFlag rrFlag = (ReadRecipientGroup.RRGroupFlag)flag;
        if ((rrFlag & ReadRecipientGroup.RRGroupFlag.Reserved) > 0)
        {
            return string.Format("<a href='#' onclick=\"CancelScheduledMailing(event, '{0}'); return false\">{1}</a>", mrgId.ToString(), GetLocalResourceObject("CancelScheduled").ToString());
        }
        else if ((rrFlag & ReadRecipientGroup.RRGroupFlag.Canceled) > 0)
        {
            return "-";
        }
        else
        {
            string addresses = "";
            const int MaxRecipients = 5;
            int nRcpt = 0;
            ReadRecipientGroup readRecipient = new ReadRecipientGroup(mrgId);
            foreach (ReadRecipient recipient in readRecipient.GetReadRecipient())
            {
                bool read = recipient.Read;
                string address = recipient.Address;
                if (!read && IsMyDomain(address))
                {
                    if (addresses == "") addresses = address;
                    else addresses += string.Format(", {0}", address);
                    nRcpt++;
                }
                if (nRcpt > MaxRecipients)
                {
                    addresses += ", ......";
                    break;
                }
            }

            return (addresses != "") ? string.Format("<a href='#' onclick=\"CancelGroupSentMessage(event, '{0}', '{1}');return false;\">{2}</a>", mrgId.ToString(), WebUtil.EncodeJsString2(addresses), GetLocalResourceObject("CancelSent").ToString()) : "-";
        }
    }

    private static bool IsMyDomain(string address)
    {
        string domain = WebUser.CurrentUser.MailAddress.Split('@')[1];
        if (address.LastIndexOf(domain) != -1)
        {
            return true;
        }
        return false;
    }

    #endregion
}