using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using TABS.MailCarrier.Crypt;
using TABS.MailCarrier.StgBase;
using TABS.MailCarrier.WebSDK;
using TABS.MailCarrier.WebSDK.Filebox;
using TABS.MailCarrier.WebSDK.Mail;
using TABS.MailCarrier.WebSDK.User;

public partial class External_SpamList : System.Web.UI.Page
{
    protected Guid _duId = Guid.Empty;

    protected override void InitializeCulture()
    {
        // 인증된 경우 로그인 시 선택된 언어로 동작하고 인증되지 않은 경우 브라우저 언어로 동작한다.
        if (HttpContext.Current.User.Identity.IsAuthenticated)
        {
            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)
        {
            string encStr = WebParam.GetStrParamValue("mid");
            if (encStr.Length > 0)
            {
                string decStr;
                if (CryptData.Decrypt(encStr, out decStr))
                {
                    string[] decStrs = decStr.Split('|');
                    if (decStrs.Length == 3)
                    {
                        DateTime validDate = DateTime.Parse(decStrs[0]);
                        if (validDate > DateTime.Now)
                        {
                            try
                            {
                                _duId = new Guid(decStrs[1]);
                                int hashValue = int.Parse(decStrs[2].Substring(0, decStrs[2].IndexOf('\0')));
                                if (hashValue == GetHashedAddr(decStrs[1]))
                                {
                                    Session["SpamList-DuId"] = _duId;
                                    DomainUser user = new DomainUser(_duId);
                                    ToAddrLabel.Text = user.MailAddress;
                                    ExpireLabel.Visible = false;
                                }
                                else
                                {
                                    _duId = Guid.Empty;
                                }
                            }
                            catch
                            {
                                _duId = Guid.Empty;
                            }
                        }
                    }
                }
            }
            else
            {
                try
                {
                    Session["SpamList-DuId"] = _duId = WebUser.CurrentUser.DomainUserID;
                    ToAddrLabel.Text = WebUser.CurrentUser.MailAddress;
                    ExpireLabel.Visible = false;
                }
                catch
                {
                }
            }

            SpamMsgDataSource.SelectParameters[0].DefaultValue = _duId.ToString();
        }
        else
        {
            try
            {
                _duId = (Guid)Session["SpamList-DuId"];
            }
            catch
            {
                _duId = Guid.Empty;
            }
        }
    }

    protected void RefreshButton_Click(object sender, EventArgs e)
    {
        MsgGridView.DataBind();
        // Sys.Application.add_load()에서 처리하는 방식으로 변경
        //ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "RefreshScript", "BindEventMsgAction();", true);
    }

    [WebMethod]
    public static bool GetMail(int id, string duid, bool forwardChecked)
    {
        Guid duId = new Guid(duid);
        if (duId.Equals(Guid.Empty)) return false;

        bool retval = false;
        using (SqlConnection conn = new SqlConnection(GlobalConfig.ConnString))
        {
            DataSet ds = Mcsp.McSpamboxLogSelectById(conn, id);
            if (ds.Tables[0].Rows.Count == 1)
            {
                DataRow row = ds.Tables[0].Rows[0];
                DateTime recvTime = (DateTime)row["sb_time"];
                FileboxFile ff = new FileboxFile((Guid)row["sb_fl_id"]);
                ff.Load();

                UserMailbox um = new UserMailbox(duId);
                Mailbox mailbox = um.FindMailbox(Mailbox.INBOX);

                Guid newMsgId = Guid.NewGuid();
                TABS.MailCarrier.AuxLib.FileGroup fileGroup = new TABS.MailCarrier.AuxLib.FileGroup(GlobalConfig.ConnString, GlobalConfig.WebShareTempPath);
                TABS.MailCarrier.AuxLib.MailboxMsg mm = new TABS.MailCarrier.AuxLib.MailboxMsg(GlobalConfig.ConnString, fileGroup);

                bool processed = false;
                if (!forwardChecked)
                {
                    // 스팸 알리미 파일함에서 메일함으로 가져오는 경우 그룹 처리를 수행한다.
                    mm.SetInReplyToGroup(duId);
                    if (mm.SaveIntoFolder(ff.Path, newMsgId, mailbox.RootFolder.ID, Mcsp.MsgNewFlag.NotRead, Mcsp.MsgActionFlag.Spam, "", recvTime.ToUniversalTime()))
                    {
                        processed = true;
                    }
                }
                else
                {
                    // 포워드/메일규칙 적용을 위해 SMTPS를 이용해 재전송한다.
                    Guid smtpsServerId = GlobalConfig.SmtpsSelector.GetSmtpsId();
                    if (mm.SendToSmtpSender(smtpsServerId, ff.Path, Guid.NewGuid(), (string)row["sb_fromaddr"], (string)row["sb_toaddr"], "", DateTime.Now.AddMinutes(-30)))
                    {
                        processed = true;
                    }
                }
                if (processed)
                {
                    try
                    {
                        conn.Open();
                        Mcsp.McSpamboxLogUpdateFlag(conn, id, 2); // 전달 완료 플래그 셋
                        retval = true;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
        return retval;
    }

    [WebMethod]
    public static void AddSafeList(string duid, string category, string addrValue)
    {
        Guid duId = new Guid(duid);
        if (duId.Equals(Guid.Empty)) return;

        Sender mailSender = new Sender();
        mailSender.Type = Sender.SenderType.Safe;
        if (category == "mail")
        {
            mailSender.AddrType = Sender.AddressType.MailAddress;
            mailSender.Value = addrValue;
        }
        else
        {
            mailSender.AddrType = Sender.AddressType.Domain;
            mailSender.Value = addrValue;
        }
        DomainUser user = new DomainUser(duId);
        user.AddSafeBlockSender(mailSender);        
        WebOperationLog.Write(user.MailAddress, HttpContext.Current.Request.UserHostAddress, "M/External/AddSafeList.aspx", "Add", mailSender.Value);
    }

    protected string GetFromAddr(string addr)
    {
        return addr.Replace("@", "@&#8203").Replace(".", ".&#8203");
    }

    protected string GetSpamboxFlag(int id, int flag)
    {
        string flagStr = "";
        if ((flag & 2) > 0)
        {
            flagStr = GetLocalResourceObject("FlagValue3").ToString();       // 전달 완료
        }
        else if ((flag & 1) > 0)
        {
            flagStr = GetLocalResourceObject("FlagValue1").ToString();       // 알림 처리
        }
        else
        {
            flagStr = GetLocalResourceObject("FlagValue2").ToString();       // 미처리
        }
        return string.Format("<span data-status-msgid='{0}'>{1}</span>", id, flagStr);
    }

    protected string GetActionLink(int id, string mailFrom)
    {
        return string.Format("<span class=\"fa-solid fa-share\"></span> <span data-msg-action1 data-msg-id=\"{0}\" data-msg-from='{1}'>{2}</span>&nbsp;&nbsp;" +
            "<span class=\"fa-solid fa-envelope-circle-check\"></span> <span data-msg-action2 data-msg-id=\"{0}\" data-msg-from='{1}'>{3}</span>", 
            id, WebUtil.EncodeJsString2(mailFrom), 
            GetLocalResourceObject("Action1").ToString(), GetLocalResourceObject("Action2").ToString());
    }

    private int GetHashedAddr(string key)
    {
        Int64 hashValue = 0;
        foreach (char c in key.ToCharArray())
        {
            hashValue = 37 * hashValue + c;
        }
        hashValue %= 997;
        return (int)hashValue;
    }

    
}