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;

/// <summary>
/// View.aspx 파라미터 
///   board (필수, GUID) - 게시판 ID
///   article (필수, int) - 게시글 ID
///   page (선택) - 페이지 번호(0에서 시작)
///   searchCategoty (선택) - 검색 카테고리(subject, author, content)
///   searchKeyword (선택) - 검색 키워드
/// </summary>
public partial class Board_One2one_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 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.SetMcCommonCss2(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");
        _newPageParams = string.Format("board={0}&article={1}&page={2}&searchCategoty={3}&searchKeyword={4}", _boardId, _articleId, _page, _searchCategoty, Server.UrlEncode(_searchKeyword));
        _listPageParams = string.Format("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.Answer | Board.RsAccessFlag.Admin)) > 0 ||            // 답변 권한 또는 관리 권한 보유
                ((accessFlag & Board.RsAccessFlag.Question) > 0 && article.GroupCode == WebUser.CurrentUser.DomainUserID) ||       // 질문자 권한과 본인 질문글 그룹
                (article.Flag & Article.AttrFlag.FixedTop) > 0      // 고정글
                )
                && AppSetting.PassDisplayBoardFilter(_boardId, WebUser.CurrentUser.MailAddress))
            {
                LoadArticle(article);
                // 답변 : 고정글 답변 못 담
                BootstrapUtil.EnableButton(replyToolButton, ((article.Flag & Article.AttrFlag.FixedTop) > 0) ? false : true);
            }

            // 글 수정 및 삭제 가능 여부
            if (article.AuthorID == WebUser.CurrentUser.UserAccount || (accessFlag & Board.RsAccessFlag.Admin) > 0)     // 글작성자 본인 또는 Admin
            {
                BootstrapUtil.EnableButton(editToolButton, true);
                BootstrapUtil.EnableButton(deleteToolButton, true);
            }
        }
    }

    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 (!(article.AuthorID == WebUser.CurrentUser.UserAccount || (accessFlag & Board.RsAccessFlag.Admin) > 0))
        {
            // 게시판에 글을 게시할 권한이 없습니다.
            Response.Redirect("~/Error.aspx?code=15", true);
            return;
        }

        article.Remove();
        Response.Redirect("List.aspx?" + _listPageParams);
    }

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

        SubjectLabel.Text = article.Subject;
        WriteDate.Text = WebUser.CurrentUser.ToLocalTime(article.Date).ToString();
        Author.Text = ((article.Flag & Article.AttrFlag.Anonymous) > 0) ? GetGlobalResourceObject("Board", "Anonymous").ToString() :
            string.Format("{0} ({1})", article.AuthorName, article.AuthorID);
        MsgBodyHolder.Controls.Add(new LiteralControl(article.Body));

        LoadAttachedFiles(article.ID, article.Attachments);

        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();
        }
    }
        
}