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 TABS.MailCarrier.WebSDK;
using TABS.MailCarrier.WebSDK.Board;
using TABS.MailCarrier.WebSDK.User;

/// <summary>
/// View.aspx 파라미터 
///   board (필수, GUID) - 게시판 ID
///   article (필수, int) - 게시글 ID
///   page (선택) - 페이지 번호(0에서 시작)
///   searchCategoty (선택) - 검색 카테고리(subject, author, content)
///   searchKeyword (선택) - 검색 키워드
/// </summary>
public partial class Board_View : System.Web.UI.Page
{
    protected Guid _boardId;                // 게시판 ID
    protected int _articleId;               // 게시글 ID
    protected string _page;
    protected string _searchCategoty;
    protected string _searchKeyword;
    protected string _newPageParams;
    protected string _listPageParams;

    protected delegate string getComment(string comment, string questionAuthorName);
    protected getComment GetComment = null;

    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)
    {
        _boardId = WebParam.GetGuidParamValue("board");
        _articleId = WebParam.GetIntParamValue("article");
        _page = WebParam.GetStrParamValue("page");
        _searchCategoty = WebParam.GetStrParamValue("searchCategoty");
        _searchKeyword = WebParam.GetStrParamValue("searchKeyword");

        if (AppSetting.UseBoardCommentLineBreak)
            GetComment = GetCommentLineBreak;
        else
            GetComment = GetCommentNoLineBreak;

        if (WebParam.GetBooleanParamValue("searchAll", false))
        {
            _newPageParams = string.Format("board={0}&article={1}", _boardId, _articleId);
            _listPageParams = string.Format("List2.aspx?board={0}&page={1}&searchCategoty={2}&searchKeyword={3}", _boardId, _page, _searchCategoty, Server.UrlEncode(_searchKeyword));
        }
        else
        {
            _newPageParams = string.Format("board={0}&article={1}&page={2}&searchCategoty={3}&searchKeyword={4}", _boardId, _articleId, _page, _searchCategoty, Server.UrlEncode(_searchKeyword));
            _listPageParams = string.Format("List.aspx?board={0}&page={1}&searchCategoty={2}&searchKeyword={3}", _boardId, _page, _searchCategoty, Server.UrlEncode(_searchKeyword));
        }
        Page.Title = AppSetting.GetTitleInfo(Request).Title;

        if (!IsPostBack)
        {
            Article article = new Article(_articleId);
            article.Load();

            Board.RsAccessFlag accessFlag = Board.GetAccessFlag(WebUser.CurrentUser.DomainUserID, _boardId);
            if (accessFlag != Board.RsAccessFlag.None && AppSetting.PassDisplayBoardFilter(_boardId, WebUser.CurrentUser.MailAddress))
            {
                LoadArticle(article);
            }

            if ((accessFlag & (Board.RsAccessFlag.Write | Board.RsAccessFlag.Admin)) > 0)
            {
                BootstrapUtil.EnableButton(replyToolButton, true);
                AddCommentButton.Enabled = true;
                AddReplyCommentButton.Enabled = true;
            }
            if ((accessFlag & Board.RsAccessFlag.Admin) > 0)
            {
                BootstrapUtil.EnableButton(replyToolButton, true);
                BootstrapUtil.EnableButton(editToolButton, true);
                BootstrapUtil.EnableButton(deleteToolButton, true);
            }
        }
    }

    protected void CommentRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            CommentEx comment = (CommentEx)e.Item.DataItem;
            PlaceHolder container = (PlaceHolder)e.Item.FindControl("CmtItemHolder");
            if ((comment.Flag & CommentEx.CommentFlag.Deleted) > 0)
            {
                string html = string.Format("<div class='cboxDeleted'>{0}</div><div>&nbsp;</div>", GetLocalResourceObject("CmtDeleted").ToString());
                container.Controls.Add(new LiteralControl(html));
            }
            else
            {
                StringBuilder html = new StringBuilder();
                html.Append(string.Format(
                    "<div class='cboxAuthor'>{0}</div>" +
                    "<div class='cboxSubject'>{1}</div>" +
                    "<div class='text-right'>" +
                        "<span class='small text-muted'>{2:g}</span> " +
                        "<span class='small'><a class='text-muted' href='#' onclick='ReplyCommentLinkClick(this, {3});return false'>{4}</a></span> ", 
                        Server.HtmlEncode(comment.AuthorName), GetComment(comment.Subject, comment.QuestionAuthorName),
                        WebUser.CurrentUser.ToLocalTime(comment.Date), comment.ID, GetLocalResourceObject("CmtTool1").ToString()));                
                if (comment.AuthorID == WebUser.CurrentUser.UserAccount)
                {
                    html.Append(string.Format(
                        "<span class='small'><a class='text-muted' href='#' onclick='RemoveCommentLinkClick({0});return false'>{1}</a></span>",
                            comment.ID, GetLocalResourceObject("CmtTool2").ToString()));
                }
                html.Append("</div>");
                container.Controls.Add(new LiteralControl(html.ToString()));
            }
        }
    }

    protected void RefreshButton_Click(object sender, EventArgs e)
    {
        Article article = new Article(_articleId);
        LoadComments(article.CommentExs);
    }

    protected void DeleteButton_Click(object sender, EventArgs e)
    {
        Article article = new Article(_articleId);
        article.Load();
        Board.RsAccessFlag accessFlag = Board.GetAccessFlag(WebUser.CurrentUser.DomainUserID, article.BoardID);
        // 글 작성자 본인(쓰기 권한 필요) 및 관리자만 글을 수정할 수 있다.
        if (!(((accessFlag & Board.RsAccessFlag.Write) > 0 && article.AuthorID == WebUser.CurrentUser.UserAccount) || (accessFlag & Board.RsAccessFlag.Admin) > 0))
        {
            // 게시판에 글을 게시할 권한이 없습니다.
            Response.Redirect("~/Error.aspx?code=15", true);
            return;
        }
        
        article.Remove();
        WebOperationLog.Write(WebUser.CurrentUser.MailAddress, Request.UserHostAddress, "M/Board/View.aspx", "Remove", string.Format("BID:{0}, AID:{1}", _boardId.ToString(), article.ID));
        Response.Redirect(_listPageParams);
    }

    protected void RecommendButton_Click(object sender, EventArgs e)
    {
        Article article = new Article(_articleId);
        if (!article.SetRecommend(WebUser.CurrentUser.DomainUserID))
        {
            ScriptManager.RegisterClientScriptBlock(this, Page.GetType(), "ShowWarning", string.Format("ShowMessage('{0}');", GetLocalResourceObject("Msg05").ToString()), true);
        }
        article.Load();
        ReadCountLabel.Text = string.Format(GetLocalResourceObject("ReadCountLabel").ToString(), article.ReadCount);
        RecommendCountLabel.Text = string.Format(GetLocalResourceObject("RecommendCountLabel").ToString(), article.RecommendCount);
        LoadComments(article.CommentExs);
    }

    protected void AddCommentButton_Click(object sender, EventArgs e)
    {
        Article article = new Article(_articleId);

        Comment comment = new Comment();
        comment.AuthorID = WebUser.CurrentUser.UserAccount;
        comment.AuthorName = WebUser.CurrentUser.Name;
        comment.Subject = CommentTextBox.Value;

        article.WebsiteAppUrl = WebParam.GetCurrentWebAppUrl();
        article.WebsiteAppUrl1 = AppSetting.GetTitleInfo(Request)["website1"];
        article.AddComment(comment, AppSetting.BoardCommentTemplateFile);

        CommentTextBox.Value = "";
        LoadComments(article.CommentExs);
    }

    protected void AddReplyCommentButton_Click(object sender, EventArgs e)
    {
        int commentId = int.Parse(CommentId.Value);
        CommentEx qcomment = new CommentEx(commentId);
        qcomment.Load();
        if (qcomment.AuthorID == "") return;    // 댓글이 없는 경우 바로 리턴한다.

        CommentEx rcomment = new CommentEx();
        rcomment.AuthorID = WebUser.CurrentUser.UserAccount;
        rcomment.AuthorName = WebUser.CurrentUser.Name;
        rcomment.Subject = ReplyCommentTextBox.Value;
        if (qcomment.TopLevel)
        {
            // 최상위 댓글에 대한 답글
            rcomment.TopQuestionID = commentId;
            rcomment.QuestionAuthorID = qcomment.AuthorID;
            rcomment.QuestionAuthorName = "";       // 질문자 이름 출력을 않기 위해
        }
        else
        {
            // 대댓글에 대한 답글
            rcomment.TopQuestionID = qcomment.TopQuestionID;
            rcomment.QuestionAuthorID = qcomment.AuthorID;
            rcomment.QuestionAuthorName = qcomment.AuthorName;
        }

        Article article = new Article(_articleId);
        article.WebsiteAppUrl = WebParam.GetCurrentWebAppUrl();
        article.WebsiteAppUrl1 = AppSetting.GetTitleInfo(Request)["website1"];
        article.AddCommentEx(rcomment, AppSetting.BoardCommentTemplateFile);
        LoadComments(article.CommentExs);
    }

    protected void RemoveCommentButton_Click(object sender, EventArgs e)
    {
        int commentId = int.Parse(CommentId.Value);
        Comment comment = new Comment(commentId);
        comment.Remove();

        Article article = new Article(_articleId);
        article.Load();
        LoadComments(article.CommentExs);
    }

    private void LoadArticle(Article article)
    {
        article.SetRead(WebUser.CurrentUser.DomainUserID);

        SubjectLabel.Text = article.Subject;
        WriteDate.Text = WebUser.CurrentUser.ToLocalTime(article.Date).ToString();
        AuthorName.Text = article.AuthorName;
        AuthorID.Text = article.AuthorID;
        MsgBodyHolder.Controls.Add(new LiteralControl(article.Body));
        ReadCountLabel.Text = string.Format(GetLocalResourceObject("ReadCountLabel").ToString(), article.ReadCount);
        RecommendCountLabel.Text = string.Format(GetLocalResourceObject("RecommendCountLabel").ToString(), article.RecommendCount);

        LoadAttachedFiles(article.ID, article.Attachments);
        LoadComments(article.CommentExs);

        if (article.AuthorID == WebUser.CurrentUser.UserAccount)
        {
            BootstrapUtil.EnableButton(editToolButton, true);
            BootstrapUtil.EnableButton(deleteToolButton, true);
        }
    }

    private void LoadAttachedFiles(int articleId, Attachment[] attachments)
    {
        int attachCount = 0;
        long attachSize = 0;
        ExtIconMap iconMap = new ExtIconMap();
        StringBuilder attchSb = new StringBuilder();
        foreach (Attachment attachment in attachments)
        {
            if (attachment.Type == Attachment.AttachType.Attachment)
            {
                string icon = string.Format("<img src=\"../Images/Ext/{0}\" />", iconMap.GetIconName(attachment.FileName));
                string link = string.Format("<a href=\"Download.ashx?article={4}&attach={1}\" class='list-group-item'>{0} {2} ({3})</a>",
                    icon, attachment.ID.ToString(), attachment.FileName, WebUtil.GetFormattedFileSize(attachment.Size), articleId.ToString());
                attchSb.Append(link);
                attachCount++;
                attachSize += attachment.Size;
            }
        }

        if (attachCount > 0)
        {
            BootstrapUtil.CollapseControl(attachPanel, false);
            AttachSummaryLabel.Text = string.Format(GetLocalResourceObject("Msg03").ToString(), attachCount, WebUtil.GetFormattedFileSize((long)attachSize));
            AttachListTag.Text = attchSb.ToString();
        }
    }

    private void LoadComments(CommentEx[] comments)
    {
        CommentCountLabel.Text = comments.Length.ToString();
        CommentRepeater.DataSource = comments;
        CommentRepeater.DataBind();
    }

    protected string GetCommentNoLineBreak(string comment, string questionAuthorName)
    {
        if (questionAuthorName != "")
        {
            return string.Format("<span class='cboxReplyTarget'>{0}</span> {1}", questionAuthorName, WebUtil.GetFormattedPlainText(comment, false));
        }
        else
        {
            return WebUtil.GetFormattedPlainText(comment, false);
        }
    }

    protected string GetCommentLineBreak(string comment, string questionAuthorName)
    {
        if (questionAuthorName != "")
        {
            return string.Format("<span class='cboxReplyTarget'>{0}</span> {1}", questionAuthorName, WebUtil.GetFormattedPlainText(comment, true));
        }
        else
        {
            return WebUtil.GetFormattedPlainText(comment, true);
        }
    }
}