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>
/// List.aspx 파라미터 
///   board (필수, GUID) - 게시판 ID
///   page (선택, int) - 페이지 번호(0에서 시작)
///   searchCategoty (선택) - 검색 카테고리(subject, author, content)
///   searchKeyword (선택) - 검색 키워드
/// </summary>
public partial class Board_One2one_List : System.Web.UI.Page
{
    protected Guid _boardId;
    private bool _adminRight = false;
    private Guid _groupCode = Guid.Empty;

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

        if (!IsPostBack)
        {
            _adminRight = false;
            _groupCode = Guid.Empty;
            Board.RsAccessFlag accessFlag = Board.GetAccessFlag(WebUser.CurrentUser.DomainUserID, _boardId);
            if (accessFlag == Board.RsAccessFlag.None || !AppSetting.PassDisplayBoardFilter(_boardId, WebUser.CurrentUser.MailAddress))
            {
                Response.Redirect("~/Error.aspx?code=14", true);
                return;
            }

            if ((accessFlag & Board.RsAccessFlag.Admin) > 0 || (accessFlag & Board.RsAccessFlag.Answer) > 0)
            {
                if ((accessFlag & Board.RsAccessFlag.Admin) > 0) _adminRight = true;
            }
            else if ((accessFlag & Board.RsAccessFlag.Question) > 0)
            {
                _groupCode = WebUser.CurrentUser.DomainUserID;
            }

            Board board = new Board(_boardId);
            ArticlesGridView.Columns[0].HeaderText = board.Name;

            ProcessGetParameters();
        }
    }

    /// <summary>
    /// GET 파라미터에 따라 리스트, 검색 리스트를 선택해 출력한다.
    /// </summary>
    private void ProcessGetParameters()
    {
        int pageIndex = WebParam.GetIntParamValue("page");
        ArticlesGridView.PageIndex = pageIndex;
        CategoryList.SelectedValue = WebParam.GetStrParamValue("searchCategoty");
        KeywordTextBox.Text = WebParam.GetStrParamValue("searchKeyword");
        if (KeywordTextBox.Text.Trim().Length > 0)
        {
            SelectDataSoutce(true);
            searchPanel.Attributes.Add("class", "collapse in");
        }
        else
        {
            SelectDataSoutce(false);
        }
    }

    /// <summary>
    /// 데이터 소스(일반, 검색)를 선택한다.
    /// </summary>
    /// <param name="search"></param>
    private void SelectDataSoutce(bool search)
    {
        if (search)
        {
            ArticlesGridView.DataSourceID = "SearchedArticlesDataSource";
            SearchedArticlesDataSource.SelectParameters[0].DefaultValue = _boardId.ToString();
            SearchedArticlesDataSource.SelectParameters[1].DefaultValue = CategoryList.SelectedValue;
            SearchedArticlesDataSource.SelectParameters[2].DefaultValue = KeywordTextBox.Text.Trim();
            SearchedArticlesDataSource.SelectParameters[3].DefaultValue = _groupCode.ToString();
        }
        else
        {
            ArticlesGridView.DataSourceID = "ArticlesDataSource";
            ArticlesDataSource.SelectParameters[0].DefaultValue = _boardId.ToString();
            ArticlesDataSource.SelectParameters[1].DefaultValue = _groupCode.ToString();
        }
    }

    #region Page Event Methods

    protected void ArticlesGridView_PreRender(object sender, EventArgs e)
    {
        GridView gv = (GridView)sender;
        if ((gv.ShowHeader == true && gv.Rows.Count > 0) || (gv.ShowHeaderWhenEmpty == true))
        {
            gv.HeaderRow.TableSection = TableRowSection.TableHeader;
        }
        if (gv.ShowFooter == true && gv.Rows.Count > 0)
        {
            gv.FooterRow.TableSection = TableRowSection.TableFooter;
        }
    }

    protected void SearchButton_Click(object sender, EventArgs e)
    {
        string keyword = KeywordTextBox.Text.Trim();
        if (keyword.Length > 0)
        {
            SelectDataSoutce(true);
            ArticlesGridView.PageIndex = 0;
            ArticlesGridView.DataBind();
            searchPanel.Attributes.Add("class", "collapse in");
        }
        else
        {
            SelectDataSoutce(false);
            ArticlesGridView.PageIndex = 0;
            ArticlesGridView.DataBind();
        }
    }

    protected void SearchCancelButton_Click(object sender, EventArgs e)
    {
        KeywordTextBox.Text = "";       // <- DataBind() 전 호출 필수
        SelectDataSoutce(false);
        ArticlesGridView.PageIndex = 0;
        ArticlesGridView.DataBind();
        searchPanel.Attributes.Add("class", "collapse");
    }

    #endregion

    #region ArticlesGridView Methods

    protected string GetAuthorName(string authorName, string authorID, Article.AttrFlag flag)
    {
        if (_adminRight)
        {
            return ((flag & Article.AttrFlag.Anonymous) > 0) ? authorID : authorName;
        }
        else
        {
            return ((flag & Article.AttrFlag.Anonymous) > 0) ? GetGlobalResourceObject("Board", "Anonymous").ToString() : authorName;
        }
    }

    protected string GetSubject(Article article)
    {
        StringBuilder sb = new StringBuilder();
        if ((article.Flag & Article.AttrFlag.FixedTop) > 0)
        {
            sb.Append(string.Format("<span class='text-primary'><strong>{0}</strong></span>", Server.HtmlEncode(article.Subject)));
            if (article.CommentCount > 0)
                sb.Append(string.Format(" <span class='text-primary'><strong>[{0}]</strong></span>", article.CommentCount));
        }
        else
        {
            bool newArticle = false;
            if (!article.Read)
            {
                TimeSpan timeSpan = DateTime.UtcNow - article.Date;
                if (timeSpan.TotalDays < 14) newArticle = true;
            }
            if (article.Depth > 0)
            {
                sb.Append(string.Format("<span class=\"fa-solid fa-arrow-turn-up fa-rotate-90\" style=\"margin-left:{0}px;margin-right:6px;\"></span>", article.Depth * 8));
            }

            if (newArticle)
            {
                sb.Append(string.Format("<span><strong>{0}</strong></span>", Server.HtmlEncode(article.Subject)));
                if (article.CommentCount > 0)
                    sb.Append(string.Format(" <span class='text-success'><strong>[{0}]</strong></span>", article.CommentCount));
            }
            else
            {
                sb.Append(string.Format("<span>{0}</span>", Server.HtmlEncode(article.Subject)));
                if (article.CommentCount > 0)
                    sb.Append(string.Format(" <span class='text-success'>[{0}]</span>", article.CommentCount));
            }
        }

        if (article.AttachCount > 0)
        {
            sb.Append(" <small>" + MailUtil.GetAttachFontIcon(article.AttachCount) + "</small>");
        }
        return sb.ToString();
    }

    protected string GetDate(DateTime writtenDate)
    {
        return WebUser.CurrentUser.ToLocalTime(writtenDate).ToString("d");
    }

    protected string GetClickEventFunction(int articleId)
    {
        return string.Format("ViewArticle('{0}', {1}, '{2}', '{3}', '{4}')", _boardId, ArticlesGridView.PageIndex, articleId, CategoryList.SelectedValue, WebUtil.EncodeJsString2(KeywordTextBox.Text.Trim()));
    }

    #endregion
}