using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Services;
using System.Web.UI.WebControls;
using TABS.MailCarrier.StgBase;
using TABS.MailCarrier.WebSDK;
using TABS.MailCarrier.WebSDK.Calendar;
using TABS.MailCarrier.WebSDK.Calendar.iCalendar;
using TABS.MailCarrier.WebSDK.Contact;
using TABS.MailCarrier.WebSDK.Mail;
using TABS.MailCarrier.WebSDK.User;

public partial class Mail_CallAjax : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    [WebMethod]
    public static void SetMsgFlag(string msgId, int flagValue)
    {
        Message message = new Message(new Guid(msgId));
        message.SetFlag(flagValue);
    }

    [WebMethod]
    public static int MoveMessage(string folderId, string msgIds)
    {
        int count = 0;
        Guid destFolderId = new Guid(folderId);
        foreach (string msgId in msgIds.Split('|'))
        {
            if (msgId != "")
            {
                Message message = new Message(new Guid(msgId));
                message.Move(destFolderId);
                count++;
            }
        }

        WebOperationLog.Write(WebUser.CurrentUser.MailAddress, HttpContext.Current.Request.UserHostAddress, "M/Mail/CallAjax.aspx", "MoveMessage", string.Format("to:{0} (count:{1})", folderId, count));
        return count;
    }

    [WebMethod]
    public static int DeleteMessages(string folderType, string[] msgIDs)
    {
        int count = 0;
        foreach (string msgID in msgIDs)
        {
            Message message = new Message(new Guid(msgID));
            if (folderType == Mailbox.TRASHBOX || folderType == Mailbox.SPAMBOX)
            {
                // 현재 메일박스가 휴지통이나 스팸편지함이라면 삭제처리한다.
                message.Remove();
                WebOperationLog.Write(WebUser.CurrentUser.MailAddress, HttpContext.Current.Request.UserHostAddress, "M/Mail/CallAjax.aspx", "RemoveMessage", string.Format("{0}(msg:{1})", folderType, message.ID));
            }
            else
            {
                // 휴지통으로 이동
                message.MoveToTrash(WebUser.CurrentUser.DomainUserID);
                WebOperationLog.Write(WebUser.CurrentUser.MailAddress, HttpContext.Current.Request.UserHostAddress, "M/Mail/CallAjax.aspx", "MsgMoveToTrash", string.Format("{0}(msg:{1})", folderType, message.ID));
            }
            count++;
        }
        return count;
    }

    [WebMethod]
    public static void Logout()
    {
        string clientIp;
        clientIp = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (clientIp == null) clientIp = HttpContext.Current.Request.UserHostAddress;

        DomainUser user = new DomainUser(WebUser.CurrentUser.DomainUserID);
        user.WriteWebAccessLog(2, WebUser.CurrentUser.MailAddress, clientIp);
    }

    [WebMethod]
    public static string GetSignatureEx(string id)
    {
        SignatureEx sig = new SignatureEx(new Guid(id));
        return "\r\n" + sig.Text + "\r\n";
    }

    [WebMethod]
    public static string GetSignatureEx2(string id)
    {
        SignatureEx sig = new SignatureEx(new Guid(id));
        return (sig.Html != "") ? sig.Html.Replace("id=\"mc_container\"", "") : "<p>&nbsp;</p>";
    }

    [WebMethod]
    public static void MeetingRequest(string msgId, string command)
    {
        string icsPath = "";
        Guid mmId = new Guid(msgId);
        Message msg = new Message(mmId);
        try
        {
            msg.Load();
            foreach (Attachment attach in msg.Attachments)
            {
                if (attach.ContentType == "text/calendar")
                {
                    icsPath = GlobalConfig.WebTempPath + "\\" + attach.FilePath;
                    break;
                }
            }
            if (icsPath.Length > 0)
            {
                iCalendar ical = new iCalendar();
                if (ical.LoadFile(icsPath, false))
                {
                    MeetingResponse meetResp = new MeetingResponse(WebUser.CurrentUser.DomainUserID, WebUser.CurrentUser.Name, WebUser.CurrentUser.MailAddress);
                    switch (command)
                    {
                        case "accept":      // 모임 수락
                            meetResp.AcceptReply(ical, true);
                            break;
                        case "tentitive":   // 모임 미정 상태로 수락
                            meetResp.AcceptReply(ical, false);
                            break;
                        case "decline":     // 모임 거절
                            meetResp.DeclineReply(ical);
                            break;
                    }
                }

                // 모임 알림 메시지 휴지통 이동 --> 아래 플래그 세팅으로 변경
                //Message message = new Message(mmId);
                //message.MoveToTrash(WebUser.CurrentUser.DomainUserID);

                // 모임 응답 했음 플래그 세팅
                Message srcMessage = new Message(mmId);
                srcMessage.SetActionFlag(Message.MsgActionFlag.MeetingResponse);
            }
        }
        catch (LoadFailException)
        {
            return;
        }
    }

    [WebMethod]
    public static bool SpamReport(string msgId, bool reportAsSpam, bool blockSender, string blockSenderOption)
    {
        bool retval = false;
        Message message = new Message(new Guid(msgId));
        try
        {
            // 스팸 신고 메일을 발송한다.
            if (reportAsSpam)
            {
                NewMessage.SendSpamReport(WebUser.CurrentUser.MailAddress, message);
            }
            // Block 리스트에 등록한다.
            if (blockSender)
            {
                message.Load(true);

                Sender mailSender = new Sender();
                mailSender.Type = Sender.SenderType.Block;
                if (blockSenderOption == "mail")
                {
                    mailSender.AddrType = Sender.AddressType.MailAddress;
                    mailSender.Value = message.FromAddress.Trim();
                }
                else
                {
                    mailSender.AddrType = Sender.AddressType.Domain;
                    int pos = message.FromAddress.IndexOf('@');
                    if (pos > 0) mailSender.Value = message.FromAddress.Substring(pos + 1).Trim();
                }

                if (mailSender.Value != "")
                {
                    DomainUser user = new DomainUser(WebUser.CurrentUser.DomainUserID);
                    user.AddSafeBlockSender(mailSender);
                    WebOperationLog.Write(WebUser.CurrentUser.MailAddress, HttpContext.Current.Request.UserHostAddress, "M/Mail/CallAjax.aspx", "SpamReport", "add block: " + mailSender.Value);
                }
            }

            // 스팸 메시지로 표시한다.
            message.SetActionFlag(Message.MsgActionFlag.Spam);
            // 스팸 편지함으로 이동시킨다.
            Guid folderId = MailboxFolder.GetRootFolderID(WebUser.CurrentUser.DomainUserID, Mailbox.SPAMBOX);
            message.Move(folderId);
            WebOperationLog.Write(WebUser.CurrentUser.MailAddress, HttpContext.Current.Request.UserHostAddress, "M/Mail/CallAjax.aspx", "SpamReport", string.Format("move to {0}(msg:{1})", Mailbox.SPAMBOX, message.ID));
            retval = true;
        }
        catch (InvalidLicenseException)
        {
            retval = false;
        }
        return retval;
    }

    [WebMethod]
    public static bool SetMessageReadStatus(string msgId, bool read)
    {
        bool retval = false;
        Message message = new Message(new Guid(msgId));
        try
        {
            message.SetReadStatus(read);
            retval = true;
        }
        catch { }
        return retval;
    }

}