using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using TABS.MailCarrier.WebSDK.Contact;
using TABS.MailCarrier.WebSDK.User;

public partial class Contact_List : System.Web.UI.Page
{
    protected Guid _folderId = Guid.Empty;
    protected bool _favorite = false;

    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)
    {
        _folderId = WebParam.GetGuidParamValue("folder");
        _favorite = (_folderId == Guid.Empty);
        Page.Title = AppSetting.GetTitleInfo(Request).Title;

        if (!IsPostBack)
        {
            // 폴더에 대한 사용 권한을 얻는다.
            AddressBookFolder folder = new AddressBookFolder(_folderId);
            AddressBook.RsAccessFlag accessFlag = AddressBook.GetAccessFlag(WebUser.CurrentUser.DomainUserID, folder.AddressBookID);

            if (_favorite)
            {
                // 자주 사용하는 연락처 보기
                ContactGridView.DataSourceID = "FavoriteDataSource";
                BootstrapUtil.EnableButton(newToolButton, false);
                SetGridTitle(Resources.Contact.ContactsFavorite);
            }
            else
            {
                // 일반 연락처 폴더 보기
                ContactGridView.DataSourceID = "ContactDataSource";

                // _accessFlag에 따른 UI 조정
                if ((accessFlag & AddressBook.RsAccessFlag.Write) == 0)
                {
                    BootstrapUtil.EnableButton(newToolButton, false);
                    BootstrapUtil.EnableButton(deleteToolButton, false);
                }
                if ((accessFlag & AddressBook.RsAccessFlag.Admin) == 0)
                {
                }
                if (folder.IsRootFolder && folder.Name == "개인 주소록")
                    SetGridTitle(Resources.Contact.ContactsPrivate);
                else
                    SetGridTitle(folder.Name);
            }
            int pageIndex = WebParam.GetIntParamValue("page");
            ContactGridView.PageIndex = pageIndex;
        } 
    }

    #region Page Event Methods

    protected void ContactGridView_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 DeleteButton_Click(object sender, EventArgs e)
    {
        Favorites favorites = new Favorites(WebUser.CurrentUser.DomainUserID);
        foreach (GridViewRow row in ContactGridView.Rows)
        {
            CheckBox check = (CheckBox)row.FindControl("SelectCheckBox");
            if (check.Checked)
            {
                Guid contactId = new Guid(ContactGridView.DataKeys[row.DataItemIndex - (ContactGridView.PageSize * ContactGridView.PageIndex)].Value.ToString());
                Contact contact = new Contact(contactId);
                if (_favorite)
                {
                    favorites.RemoveContact(contact);
                }
                else
                {
                    contact.Remove();
                    WebOperationLog.Write(WebUser.CurrentUser.MailAddress, Request.UserHostAddress, "M/Contact/List.aspx", "Remove", string.Format("FID:{0} CID:{1}", _folderId.ToString(), contactId.ToString()));
                }
            }
        }
        ContactGridView.DataBind();
    }

    protected void FilterComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        FilterField.Value = FilterComboBox.SelectedValue;
        ContactGridView.DataBind();
        searchPanel.Attributes.Add("class", "collapse in");
    }

    protected void SearchButton_Click(object sender, EventArgs e)
    {
        string keyword = KeywordTextBox.Text.Trim();
        SearchField.Value = keyword;
        ContactGridView.PageIndex = 0;
        ContactGridView.DataBind();
        searchPanel.Attributes.Add("class", "collapse in");
    }

    protected void SearchCancelButton_Click(object sender, EventArgs e)
    {
        FilterComboBox.SelectedIndex = 0;
        FilterField.Value = "";
        KeywordTextBox.Text = "";
        SearchField.Value = "";
        ContactGridView.PageIndex = 0;
        ContactGridView.DataBind();
        searchPanel.Attributes.Add("class", "collapse");
    }

    #endregion

    #region Grid Support Methods

    protected string GetName(string name)
    {
        return Server.HtmlEncode(name);
    }

    protected string GetPhoneNumber(Contact contact)
    {
        return (contact.HomeMobile.Length > 0) ? contact.HomeMobile : contact.JobPhone;
    }

    protected string GetActionButtons(Contact contact)
    {
        const string disabled = "disabled=\"disabled\"";
        string phoneNumber = (contact.HomeMobile.Length > 0) ? contact.HomeMobile.Trim() : contact.JobPhone.Trim();
        string phoneNumberDiabled = (phoneNumber.Length == 0) ? disabled  : "";
        string phoneNumberParam = WebUtil.EncodeJsString2(phoneNumber);
        string html1 = string.Format("<button type=\"button\" class=\"btn btn-default\" onclick=\"CallPhone(event, '{0}')\" {1}>{2}</button> ", phoneNumberParam, phoneNumberDiabled, FontIcon.ContactPhone);
        // SMS "<button type=\"button\" class=\"btn btn-default\" onclick=\"CallSms('{0}')\" {1}><span class=\"glyphicon glyphicon-phone\"></span></button> "

        string html2 = "";
        if (contact.Type == Contact.ContactType.Contact)
        {
            if (contact.Email.Trim().Length == 0)
                html2 = string.Format("<button type=\"button\" class=\"btn btn-default disabled\" onclick=\"NoAction(event)\">{0}</button>", FontIcon.ContactEmail);
            else
                html2 = string.Format("<button type=\"button\" class=\"btn btn-default\" onclick=\"OpenNewMail(event, '{0}')\">{1}</button>", contact.ID, FontIcon.ContactEmail);
        }
        else
        {
            html2 = string.Format("<button type=\"button\" class=\"btn btn-default\" onclick=\"OpenNewGroupMail(event, '{0}')\">{1}</button>", contact.ID, FontIcon.ContactEmail);
        }

        return html1 + html2;
    }

    protected string GetClickEventFunction(Contact contact)
    {
        return (contact.Type == Contact.ContactType.Contact) ? string.Format("ViewContact('{0}', {1})", contact.ID, ContactGridView.PageIndex) : "";
    }

    #endregion


    #region Internal Utility Methods

    private void SetGridTitle(string title)
    {
        ContactGridView.Columns[1].HeaderText = title;
    }

    #endregion
}