using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using TABS.MailCarrier.WebSDK;
using TABS.MailCarrier.StgBase;
using TABS.MailCarrier.WebSDK.Board;
using TABS.MailCarrier.WebSDK.Mail;

public partial class Options_WebPushOption : System.Web.UI.Page
{
    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)
    {
        if (!IsPostBack)
        {
            LoadTimeZoneList(WebUser.CurrentUser.UiLanguage);
            using (SqlConnection conn = new SqlConnection(GlobalConfig.ConnString))
            {
                conn.Open();

                DataSet ds = Mcsp.WpuUserNotifyRuleSelect(conn, WebUser.CurrentUser.DomainUserID);
                if (ds.Tables[0].Rows.Count == 1)
                    LoadNotifyRule(ds.Tables[0].Rows[0]);
                else
                    InitNotifyRule();
            }
            LoadSubscription();
        }
    }

    protected void SaveButton_Click(object sender, EventArgs e)
    {
        try
        {
            int flag = (NotificationType1.Checked) ? 1 : 2;
            long utcOffset = long.Parse(TimeZoneUtcOffset.Value);
            int weekday = 0;
            if (Weekday1.Checked) weekday += int.Parse(Weekday1.Value);
            if (Weekday2.Checked) weekday += int.Parse(Weekday2.Value);
            if (Weekday3.Checked) weekday += int.Parse(Weekday3.Value);
            if (Weekday4.Checked) weekday += int.Parse(Weekday4.Value);
            if (Weekday5.Checked) weekday += int.Parse(Weekday5.Value);
            if (Weekday6.Checked) weekday += int.Parse(Weekday6.Value);
            if (Weekday7.Checked) weekday += int.Parse(Weekday7.Value);
            long beginTime = TimeSpan.Parse(BeginTime.Text).Ticks;
            long endTime = TimeSpan.Parse(EndTime.Text).Ticks;

            using (SqlConnection conn = new SqlConnection(GlobalConfig.ConnString))
            {
                conn.Open();
                Mcsp.WpuUserNotifyRuleInsert(conn, null, WebUser.CurrentUser.DomainUserID, flag, TimeZoneTextBox.Text, utcOffset, weekday, beginTime, endTime);

                Mcsp.WpuServiceType service = Mcsp.WpuServiceType.None;
                if (MailNotifyCheckBox.Checked) service |= Mcsp.WpuServiceType.Mail;
                
                if (PrivateCalendarNotifyCheckBox.Checked) service |= Mcsp.WpuServiceType.PrivateCalendar;
                if (SharedCalendarNotifyCheckBox.Checked) service |= Mcsp.WpuServiceType.SharedCalendar;

                if (BoardNotifyCheckBox1.Checked) service |= Mcsp.WpuServiceType.NewArticle;
                if (BoardNotifyCheckBox2.Checked) service |= Mcsp.WpuServiceType.ReplyArticle;
                if (BoardNotifyCheckBox3.Checked) service |= Mcsp.WpuServiceType.Comment;

                if (ApprovalCheckBox.Checked) service |= Mcsp.WpuServiceType.Approval;

                Mcsp.WpuUserSubscriptionUpdateService(conn, WebUser.CurrentUser.DomainUserID, (int)service);
            }

            foreach (RepeaterItem item in FolderRepeater.Items)
            {
                CheckBox checkBox = item.FindControl("CheckBox") as CheckBox;
                MailboxFolder mboxFolder = new MailboxFolder(new Guid((string)checkBox.Attributes["folderId"]));
                mboxFolder.SetWebPush(checkBox.Checked);
            }

            if (AppSetting.UseBoard)
            {
                Guid userId = WebUser.CurrentUser.DomainUserID;
                Board.UnsubscribeAll(userId);
                foreach (RepeaterItem item in BoardRepeater.Items)
                {
                    CheckBox checkBox = item.FindControl("CheckBox") as CheckBox;
                    if (checkBox.Checked)
                    {
                        Guid boardId = new Guid((string)checkBox.Attributes["boardId"]);
                        Board.Subscribe(boardId, userId);
                    }                    
                }
            }

            ShowSuccessMessage(GetLocalResourceObject("RespOK").ToString());
        }
        catch
        {
            ShowWarningMessage(GetLocalResourceObject("RespERR").ToString());
        }
    }

    private void LoadNotifyRule(DataRow row)
    {
        if ((int)row["ur_flag"] == 1)
            NotificationType1.Checked = true;
        else
            NotificationType2.Checked = true;
        TimeZoneTextBox.Text = (string)row["ur_timezone"];
        TimeZoneUtcOffset.Value = ((long)row["ur_utcoffset"]).ToString();
        int weekDay = (int)row["ur_weekday"];
        Weekday1.Checked = (int.Parse(Weekday1.Value) & weekDay) > 0;
        Weekday2.Checked = (int.Parse(Weekday2.Value) & weekDay) > 0;
        Weekday3.Checked = (int.Parse(Weekday3.Value) & weekDay) > 0;
        Weekday4.Checked = (int.Parse(Weekday4.Value) & weekDay) > 0;
        Weekday5.Checked = (int.Parse(Weekday5.Value) & weekDay) > 0;
        Weekday6.Checked = (int.Parse(Weekday6.Value) & weekDay) > 0;
        Weekday7.Checked = (int.Parse(Weekday7.Value) & weekDay) > 0;
        BeginTime.Text = new TimeSpan((long)row["ur_begintime"]).ToString("c");
        EndTime.Text = new TimeSpan((long)row["ur_endtime"]).ToString("c");
    }

    private void InitNotifyRule()
    {
        NotificationType1.Checked = true;
        string timeZone;
        TimeSpan tzOffset;
        GetTimezoneInfo(out timeZone, out tzOffset);
        TimeZoneTextBox.Text = timeZone;
        TimeZoneUtcOffset.Value = tzOffset.Ticks.ToString();
        Weekday1.Checked = true;
        Weekday2.Checked = true;
        Weekday3.Checked = true;
        Weekday4.Checked = true;
        Weekday5.Checked = true;
        BeginTime.Text = new TimeSpan(9, 0, 0).ToString("c");
        EndTime.Text = new TimeSpan(18, 0, 0).ToString("c");
    }

    private void LoadTimeZoneList(string defLang)
    {
        DateTimeFormatInfo dateFormats = CultureInfo.CurrentCulture.DateTimeFormat;
        ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones();

        if (defLang == "ko")
        {
            foreach (TimeZoneInfo timeZone in timeZones)
            {
                TimeZoneList.Items.Add(new ListItem(timeZone.DisplayName, timeZone.Id));
            }
        }
        else
        {
            foreach (TimeZoneInfo timeZone in timeZones)
            {
                int zoneLen = timeZone.DisplayName.IndexOf(")");
                string timeZoneName = timeZone.DisplayName.Substring(0, zoneLen + 1);
                TimeZoneList.Items.Add(new ListItem(timeZoneName + " " + timeZone.Id, timeZone.Id));
            }
        }

        foreach (ListItem item in TimeZoneList.Items)
        {
            if (item.Value == TimeZoneInfo.Local.Id) item.Selected = true;
        }
    }

    private void GetTimezoneInfo(out string timeZone, out TimeSpan offset)
    {
        TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneList.SelectedValue);
        offset = tzi.BaseUtcOffset;
        if (offset.Hours >= 0)
            timeZone = string.Format("UTC+{0:D2}:{1:D2}", offset.Hours, offset.Minutes);
        else
            timeZone = string.Format("UTC-{0:D2}:{1:D2}", Math.Abs(offset.Hours), Math.Abs(offset.Minutes));
    }

    private void ShowWarningMessage(string msg)
    {
        MsgBox.Visible = true;
        MsgBox.CssClass = "alert alert-danger";
        MsgBoxLabel.Text = msg;
    }

    private void ShowSuccessMessage(string msg)
    {
        MsgBox.Visible = true;
        MsgBox.CssClass = "alert alert-success";
        MsgBoxLabel.Text = msg;
    }

    private void LoadSubscription()
    {
        string endPoint = ((HiddenField)PreviousPage.FindControl("EndPointField")).Value;
        using (SqlConnection conn = new SqlConnection(GlobalConfig.ConnString))
        {
            conn.Open();
            DataSet ds = Mcsp.WpuUserSubscriptionSelect(conn, WebUser.CurrentUser.DomainUserID, endPoint);
            if (ds.Tables[0].Rows.Count == 1)
            {
                Mcsp.WpuServiceType serviceType = (Mcsp.WpuServiceType)ds.Tables[0].Rows[0]["ud_service"];
                MailNotifyCheckBox.Checked = ((serviceType & Mcsp.WpuServiceType.Mail) > 0);
                PrivateCalendarNotifyCheckBox.Checked = ((serviceType & Mcsp.WpuServiceType.PrivateCalendar) > 0);
                if (PrivateCalendarNotifyCheckBox.Checked)
                {
                    SharedCalendarNotifyCheckBox.Checked = ((serviceType & Mcsp.WpuServiceType.SharedCalendar) > 0);
                    SharedCalendarNotifyCheckBox.Enabled = true;
                }
                else
                {
                    SharedCalendarNotifyCheckBox.Checked = false;
                    SharedCalendarNotifyCheckBox.Enabled = false;
                }

                BoardNotifyCheckBox1.Checked = ((serviceType & Mcsp.WpuServiceType.NewArticle) > 0);
                BoardNotifyCheckBox2.Checked = ((serviceType & Mcsp.WpuServiceType.ReplyArticle) > 0);
                BoardNotifyCheckBox3.Checked = ((serviceType & Mcsp.WpuServiceType.Comment) > 0);
                ApprovalCheckBox.Checked = ((serviceType & Mcsp.WpuServiceType.Approval) > 0);
            }
            else
            {
                MailNotifyCheckBox.Checked = false;
                PrivateCalendarNotifyCheckBox.Checked = false;
                SharedCalendarNotifyCheckBox.Checked = false;
            }

            if (!AppSetting.UseCalendar)
            {
                CalendarPanel.Visible = false;
                PrivateCalendarNotifyCheckBox.Checked = false;
                SharedCalendarNotifyCheckBox.Checked = false;
            }

            if (!AppSetting.UseBoard)
            {
                BoardPanel.Visible = false;
                BoardNotifyCheckBox1.Checked = false;
                BoardNotifyCheckBox2.Checked = false;
                BoardNotifyCheckBox3.Checked = false;
            }

            if (!AppSetting.UseApproval)
            {
                ApprovalPanel.Visible = false;
                ApprovalCheckBox.Checked = false;
            }
        }
    }

    #region Mail Folders for Notification

    protected void FolderRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            MailFolderDataSource.FolderItem folder = (MailFolderDataSource.FolderItem)e.Item.DataItem;
            CheckBox checkBox = e.Item.FindControl("CheckBox") as CheckBox;
            checkBox.Checked = folder.Checked;
            if (folder.Reserved) checkBox.Enabled = false;
            checkBox.Attributes.Add("folderId", folder.ID.ToString());
        }
    }

    protected string GetIndent(int indent)
    {
        return (indent * 16 + 4).ToString();
    }

    protected string GetFolderInfo(Guid id, string folderName)
    {
        return string.Format("{0} {1}", MailUtil.GetMailboxFontIcon(folderName), MailUtil.GetMailboxDisplayName(folderName));
    }

    protected void BoardRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            BoardSubscribedDataSource.BoardItem board = (BoardSubscribedDataSource.BoardItem)e.Item.DataItem;
            CheckBox checkBox = e.Item.FindControl("CheckBox") as CheckBox;
            checkBox.Checked = board.Subscribed;
            checkBox.Attributes.Add("boardId", board.ID.ToString());
        }
    }

    #endregion

    #region AJAX Methods

    protected void PrivateCalendarNotifyCheckBox_CheckedChanged(object sender, EventArgs e)
    {
        if (PrivateCalendarNotifyCheckBox.Checked)
        {
            SharedCalendarNotifyCheckBox.Enabled = true;
        }
        else
        {
            SharedCalendarNotifyCheckBox.Checked = false;
            SharedCalendarNotifyCheckBox.Enabled = false;
        }
    }
        
    public class TzInfo
    {
        public string TzText { get; set; }
        public string TzOffset { get; set; }
    }

    [WebMethod]
    public static TzInfo GetTimezoneInfo(string tzval)
    {
        TzInfo tzInfo = new TzInfo();
        TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(tzval);
        TimeSpan offset = tzi.BaseUtcOffset;
        if (offset.Hours >= 0)
            tzInfo.TzText = string.Format("UTC+{0:D2}:{1:D2}", offset.Hours, offset.Minutes);
        else
            tzInfo.TzText = string.Format("UTC-{0:D2}:{1:D2}", Math.Abs(offset.Hours), Math.Abs(offset.Minutes));
        tzInfo.TzOffset = offset.Ticks.ToString();
        return tzInfo;
    }

    #endregion
    
}