using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TABS.MailCarrier.WebSDK;
using TABS.MailCarrier.WebSDK.Mail;
using TABS.MailCarrier.WebSDK.User;


public partial class Mail_Folders2 : System.Web.UI.Page
{
    protected string _folderData = "";

    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)
        {
            LoadFolders();
        }
    }
        
    private class FolderItem
    {
        public FolderItem(Guid folderId, string folderName, string folderDisplayName, string folderIcon)
        {
            id = folderId.ToString();
            name = folderName;
            text = folderDisplayName;
            spriteCssClass = folderIcon;
            encoded = true;
            newMsgCount = -1;
            totalMsgCount = -1;
            items = new List<FolderItem>();
            attrs = new Dictionary<string, string>();
        }

        public string id { get; set; }
        public string text { get; set; }
        public string spriteCssClass { get; set; }
        public bool encoded { get; set; }
        public bool expanded { get; set; }
        public string name { get; set; }
        public int newMsgCount { get; set; }
        public int totalMsgCount { get; set; }
        public List<FolderItem> items{ get; set; }        
        public Dictionary<string, string> attrs { get; set; }     // 사용자 추가 속성
    }

    private void LoadFolders()
    {        
        List<FolderItem> folders = new List<FolderItem>();

        folders.Add(new FolderItem(MailUtil.AllMails, MailUtil.AllMailsMailboxName, Resources.Mail.AllMails, FontIcon2.EmailAllBox));
        folders.Add(new FolderItem(MailUtil.UnreadMails, MailUtil.UnreadMailsMailboxName, Resources.Mail.UnreadMails, FontIcon2.EmailUnread));
        folders.Add(new FolderItem(MailUtil.FlaggedMails, MailUtil.FlaggedMailsMailboxName, Resources.Mail.FlaggedMails, FontIcon2.EmailFlagged));

        if (GlobalConfig.SchemaVersion >= 753)
        {
            PermitSendEx ps = new PermitSendEx(WebUser.CurrentUser.DomainID);
            if (ps.IsApplied())
            {
                PermitSendEx.PsApproverInfoList apvInfoList = ps.GetApproverInfoByDelegate(WebUser.CurrentUser.DomainUserID);
                // 승인할 메일
                if (ps.IsConfirmer(WebUser.CurrentUser.DomainUserID))
                {
                    using (SqlConnection conn = new SqlConnection(GlobalConfig.ConnString))
                    {
                        int newCount = ps.PsConfirmListGetWaitCount(conn, WebUser.CurrentUser.DomainUserID);
                        FolderItem fiApprove = new FolderItem(MailUtil.MailToApprove, MailUtil.MailToApproveMailboxName, Resources.Mail.MailToApprove, FontIcon2.EmailApproval);
                        fiApprove.newMsgCount = newCount;
                        fiApprove.expanded = true;
                        folders.Add(fiApprove);
                        // 대리자 발송 승인
                        foreach (PermitSendEx.PsApproverInfo apvInfo in apvInfoList)
                        {
                            FolderItem fi = new FolderItem(MailUtil.MailToApprove_Delegate, "", apvInfo.Name, FontIcon2.EmailFolder);
                            fi.attrs.Add("delegate", apvInfo.DomainUserID.ToString());
                            fiApprove.items.Add(fi);
                        }
                    }                    
                }
                else if (apvInfoList.Count > 0)
                {
                    // 본인이 승인자는 아니지만 대리자인 경우
                    FolderItem fiApprove = new FolderItem(MailUtil.MailToApprove, "", Resources.Mail.MailToApprove, FontIcon2.EmailApproval);
                    fiApprove.expanded = true;
                    folders.Add(fiApprove);
                    // 대리자 발송 승인
                    foreach (PermitSendEx.PsApproverInfo apvInfo in apvInfoList)
                    {
                        FolderItem fi = new FolderItem(MailUtil.MailToApprove_Delegate, apvInfo.DomainUserID.ToString(), apvInfo.Name, FontIcon2.EmailFolder);
                        fi.attrs.Add("delegate", apvInfo.DomainUserID.ToString());
                        fiApprove.items.Add(fi);
                    }
                }

                // 승인 대기 메일
                if (ps.IsConfirmed(WebUser.CurrentUser.DomainUserID))
                {
                    folders.Add(new FolderItem(MailUtil.MailWaitForApproval, MailUtil.MailWaitForApprovalMailboxName, Resources.Mail.MailWaitForApproval, FontIcon2.EmailApproval));
                }
            }
        }

        UserMailbox userMbox = new UserMailbox(WebUser.CurrentUser.DomainUserID);
        foreach (Mailbox mailbox in userMbox.Mailboxes)
        {
            MailboxFolder folder = mailbox.RootFolder;
            string folderDisplayName, folderIcon;
            if (mailbox.Reserved) {
                folderDisplayName = MailUtil.GetMailboxDisplayName(folder.Name);
                folderIcon = MailUtil.GetMailboxFontIcon2(folder.Name);
            }
            else
            {
                folderDisplayName = folder.Name;
                folderIcon = FontIcon2.EmailFolder;
            } 
            FolderItem fi = new FolderItem(folder.ID, folder.Name, folderDisplayName, folderIcon);
            fi.newMsgCount = folder.NewMessageCount;
            fi.totalMsgCount = folder.MessageCount;
            folders.Add(fi);
            TraverseSubFolders(fi, folder);

            // 수신 확인 추가
            if (folder.Name == Mailbox.SENTBOX)
            {
                folders.Add(new FolderItem(MailUtil.ReadRecipients, MailUtil.ReadRecipientsMailboxName, Resources.Mail.ReadRecipientsMailbox, FontIcon2.EmailReadReceipt));
            }
        }

        DomainUser user = new DomainUser(WebUser.CurrentUser.DomainUserID);
        if (user.SpamOption.UseSpamNotifier)
        {
            folders.Add(new FolderItem(MailUtil.SpamNotification, MailUtil.SpamNotificationMailboxName, Resources.Mail.SpamNotifybox, FontIcon2.EmailSpambox));
        }

        folderViewData.Value = JsonConvert.SerializeObject(folders);
    }

    private void TraverseSubFolders(FolderItem parentFi, MailboxFolder folder)
    {
        foreach (MailboxFolder subfolder in folder.SubFolders)
        {
            FolderItem fi = new FolderItem(subfolder.ID, "", subfolder.Name, FontIcon2.EmailFolder);
            fi.newMsgCount = subfolder.NewMessageCount;
            fi.totalMsgCount = subfolder.MessageCount;
            parentFi.items.Add(fi);
            TraverseSubFolders(fi, subfolder);
        }
    }

}