using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TABS.MailCarrier.WebSDK;
using TABS.MailCarrier.WebSDK.Board;

public partial class Board_Folders : System.Web.UI.Page
{
    protected class BoardItem
    {
        public Guid ID { get; set; }
        public string Name { get; set; }
        public long UnreadCount { get; set; }
        public bool IsFolder { get; set; }
        public int Indent { get; set; }
        public string BoardType { get; set; }
    }

    /// <summary>
    /// 내부적으로 트리를 구성한 후 출력용 리스트를 최종 구성한다.
    /// </summary>
    private class BoardNode
    {
        public BoardItem Item = new BoardItem();
        public List<BoardNode> Nodes = new List<BoardNode>();
    }

    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)
    {
        Page.Title = AppSetting.GetTitleInfo(Request).Title;

        if (!IsPostBack)
        {
            //LoadBoardsOneDepthFolder();
            LoadBoardsFreeDepthFolder();
        }
    }

    /// <summary>
    /// 1 레벨 폴더를 지원 -> 사용되지 않음
    ///   - 1:1 게시판은 지원하지 않는다.
    /// </summary>
    private void LoadBoardsOneDepthFolder()
    {
        string folderName = "";
        UserBoard userBoard = new UserBoard(WebUser.CurrentUser.DomainUserID, true);
        List<BoardItem> boards = new List<BoardItem>();
        foreach (Board board in userBoard.ShareBoards)
        {
            if (board.Type == Board.BoardType.General && board.AccessFlag != Board.RsAccessFlag.None)
            {
                BoardItem bitem = new BoardItem();
                bitem.ID = board.ID;
                bitem.Name = board.Name;
                bitem.UnreadCount = board.UnreadCount;
                bitem.IsFolder = false;
                bitem.Indent = 0;

                if (board.FolderName != "")
                {                    
                    if (board.FolderName != folderName)
                    {
                        BoardItem fitem = new BoardItem();
                        fitem.ID = Guid.Empty;
                        fitem.Name = board.FolderName;
                        fitem.UnreadCount = 0;
                        fitem.IsFolder = true;
                        fitem.Indent = 0;
                        boards.Add(fitem);
                        folderName = board.FolderName;
                    }
                    bitem.Indent = 16;
                }
                boards.Add(bitem);                
            }
        }
        FolderRepeater.DataSource = boards;
        FolderRepeater.DataBind();
    }

    /// <summary>
    /// \ 문자로 구분되는 다계층 폴더 구조를 출력
    ///   - 1:1 게시판은 지원하지 않는다.
    /// </summary>
    private void LoadBoardsFreeDepthFolder()
    {
        string userEmail = WebUser.CurrentUser.MailAddress;
        BoardNode rootNode = new BoardNode();
        UserBoard userBoard = new UserBoard(WebUser.CurrentUser.DomainUserID, true);
        foreach (Board board in userBoard.ShareBoards)
        {
            if (board.AccessFlag != Board.RsAccessFlag.None && AppSetting.PassDisplayBoardFilter(board.ID, userEmail))
            {
                BoardNode boardNode = new BoardNode();
                boardNode.Item.ID = board.ID;
                boardNode.Item.Name = board.Name;
                boardNode.Item.UnreadCount = board.UnreadCount;
                boardNode.Item.IsFolder = false;
                boardNode.Item.Indent = 0;
                boardNode.Item.BoardType = board.Type.ToString();

                BoardNode folderNode = GetFolderNode(rootNode, board.FolderName);
                if (folderNode != null)
                    folderNode.Nodes.Add(boardNode);
                else
                    rootNode.Nodes.Add(boardNode);
            }
        }

        List<BoardItem> boardList = new List<BoardItem>();
        if (AppSetting.PassDisplayBoardFilter(userEmail))
        {
            // 전체 검색 항목 생성
            BoardItem searchAllItem = new BoardItem();
            searchAllItem.ID = new Guid("{3E58F816-79C0-450B-B5E7-A49650943A83}");
            searchAllItem.Name = Resources.Board.SearchAllType;
            searchAllItem.UnreadCount = 0;
            searchAllItem.IsFolder = false;
            searchAllItem.Indent = 0;
            searchAllItem.BoardType = "SearchAll";
            boardList.Add(searchAllItem);
        }
        MakeBoardItemList(boardList, rootNode, 0);

        FolderRepeater.DataSource = boardList;
        FolderRepeater.DataBind();
    }

    private BoardNode GetFolderNode(BoardNode parentNode, string boardFolderName)
    {
        BoardNode findNode = null;
        string[] folderNameList = boardFolderName.Split('\\');
        foreach (string folderName in folderNameList)
        {
            if (folderName.Length > 0)
            {
                string name = folderName;
                string lastChar = folderName.Substring(folderName.Length - 1);
                if (lastChar == "<")
                {
                    name = folderName.Substring(0, folderName.Length - 1);
                }

                findNode = FindNodeByText(parentNode, name);
                if (findNode == null)
                {
                    findNode = new BoardNode();
                    findNode.Item.ID = Guid.Empty;
                    findNode.Item.Name = name;
                    findNode.Item.UnreadCount = 0;
                    findNode.Item.IsFolder = true;
                    findNode.Item.Indent = 0;
                    parentNode.Nodes.Add(findNode);
                }
                parentNode = findNode;
            }
        }
        return findNode;
    }

    private BoardNode FindNodeByText(BoardNode boardNode, string text)
    {
        BoardNode findNode = null;
        foreach (BoardNode node in boardNode.Nodes)
        {
            if (node.Item.IsFolder && node.Item.Name == text)
            {
                findNode = node;
                break;
            }
        }
        return findNode;
    }

    private void MakeBoardItemList(List<BoardItem> boardList, BoardNode parentNode, int indent)
    {
        foreach (BoardNode node in parentNode.Nodes)
        {
            if (node.Item.IsFolder)
            {
                node.Item.Indent = indent;
                boardList.Add(node.Item);
                MakeBoardItemList(boardList, node, indent + 16);
            }
            else
            {
                node.Item.Indent = indent;
                boardList.Add(node.Item);
            }
        }
    }

    protected string GetIndent(bool isFolder)
    {
        return (isFolder) ? "0" : "16";
    }

    protected string GetBoardInfo(bool isFolder, string name)
    {
        if (isFolder)
        {
            return string.Format("<img src='../Images/Board/folder_16.gif' alt='' /> {0}", Server.HtmlEncode(name));
        }
        else
        {
            return string.Format("<img src='../Images/Board/list.gif' alt='' /> {0}", Server.HtmlEncode(name));
        }
    }

    protected string GetBoardInfoEx(bool isFolder, string name)
    {
        if (isFolder)
        {
            return string.Format("{0} {1}", FontIcon.BoardFolder, Server.HtmlEncode(name));
        }
        else
        {
            return string.Format("{0} {1}", FontIcon.Board, Server.HtmlEncode(name));
        }
    }

    protected string GetUnreadCount(long unReadCount)
    {
        return (unReadCount > 0) ? string.Format("<span class='badge mc-badge'>{0}</span>", unReadCount) : "";
    }

    protected string GetClickEventFunction(Guid id, string boardType)
    {
        string evtFunc = "";
        if (id != Guid.Empty) 
        {
            if (boardType == "General")
                evtFunc = string.Format("location.href = 'List.aspx?board={0}'", id.ToString());
            else if (boardType == "OneToOne")
                evtFunc = string.Format("location.href = 'One2one/List.aspx?board={0}'", id.ToString());
            else if (boardType == "SearchAll")
                evtFunc = "location.href = 'List2.aspx'";
        }
        return evtFunc;
    }
}