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.Calendar;
using Tabs = TABS.MailCarrier.WebSDK.Calendar;

public partial class Calendar_Monthly : System.Web.UI.Page
{
    protected Guid _calendarId;                 // 칼렌다 ID
    protected bool _writable, _readable;        // 권한
    private McCalendar.RsAccessFlag _accessFlag;// 권한
    private Tabs.Appointment[] _appointments = null;
    private Holiday _holiday = null;
    private string _today = "";

    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)
    {
        _calendarId = WebParam.GetGuidParamValue("cid");
        if (_calendarId == Guid.Empty) return;
        _today = WebUser.CurrentUser.GetLocalToday().ToShortDateString();

        if (!IsPostBack)
        {
            Page.Title = AppSetting.GetTitleInfo(Request).Title;

            // 일정표에 대한 사용 권한을 조회한다.
            McCalendar calendar = new McCalendar(_calendarId);
            _accessFlag = McCalendar.GetAccessFlag(WebUser.CurrentUser.DomainUserID, _calendarId);
            _writable = (_accessFlag & (McCalendar.RsAccessFlag.Write | McCalendar.RsAccessFlag.Admin)) > 0;
            _readable = _accessFlag != McCalendar.RsAccessFlag.None;

            if (!_writable)
            {
                BootstrapUtil.EnableButton(newToolButton, false);
            }

            DateTime selectedDate;
            string sdate = WebParam.GetStrParamValue("sdate");
            if (DateTime.TryParse(sdate, out selectedDate))
            {
                Calendar.VisibleDate = new DateTime(selectedDate.Year, selectedDate.Month, 1);
                SelectedDate.Value = selectedDate.ToShortDateString();
            }
            else
            {
                DateTime today = WebUser.CurrentUser.GetLocalToday();
                Calendar.VisibleDate = new DateTime(today.Year, today.Month, 1);
                SelectedDate.Value = today.ToShortDateString();
            }
            LoadDaily(DateTime.Parse(SelectedDate.Value));
            ViewState["_accessFlag"] = _accessFlag;
        }
        else
        {
            _accessFlag = (McCalendar.RsAccessFlag)ViewState["_accessFlag"];
            _writable = (_accessFlag & (McCalendar.RsAccessFlag.Write | McCalendar.RsAccessFlag.Admin)) > 0;
            _readable = _accessFlag != McCalendar.RsAccessFlag.None;
        }
    }

    protected void Calendar_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
    {
        DateTime today = WebUser.CurrentUser.GetLocalToday();
        if (today.Year == Calendar.VisibleDate.Year && today.Month == Calendar.VisibleDate.Month)
        {
            SelectedDate.Value = today.ToShortDateString();
        }
        else
        {
            SelectedDate.Value = Calendar.VisibleDate.ToShortDateString();
        }
        LoadDaily(DateTime.Parse(SelectedDate.Value));
    }

    protected void Calendar_DayRender(object sender, DayRenderEventArgs e)
    {
        // 읽기 권한은 있어야 일정을 출력한다.
        if (!_readable) return;

        if (_appointments == null)
        {
            // 일정 데이터를 로딩한다.
            McCalendar calendar = new McCalendar(_calendarId);
            _appointments = calendar.GetAppointments(Calendar.VisibleDate);
        }
        if (_holiday == null)
        {
            _holiday = HolidayCache.GetHoliday();
        }

        // 해당 일자에 속한 약속만 추출한다.
        DateTime date = e.Day.Date;
        Tabs.Appointment[] appointments = McCalendar.Select(_appointments, date);
        StringBuilder sb = new StringBuilder(2048);

        string dayColor = "";
        string holidayName;
        bool dayoff;
        bool isHoliday = _holiday.IsHoliday(date, out holidayName, out dayoff);
        if (date.DayOfWeek == DayOfWeek.Sunday || (isHoliday && dayoff))
            dayColor = (e.Day.IsOtherMonth) ? "#FF829B" : "#FF3859";
        else if (date.DayOfWeek == DayOfWeek.Saturday)
            dayColor = (e.Day.IsOtherMonth) ? "#A8CAFF" : "#5484FF";
        else
            dayColor = (e.Day.IsOtherMonth) ? "#c0c0c0" : "";

        if (appointments.Length > 0)
        {
            sb.Append(string.Format("<b style='color:{0}'>{1}</b><br /><i class=\"fa-solid fa-circle AppExistMark\"></i>", dayColor, date.Day));
        }
        else
        {
            sb.Append(string.Format("<b style='color:{0}'>{1}</b>", dayColor, date.Day));
        }
        e.Cell.Text = sb.ToString();
        string dateStr = date.ToShortDateString();
        if (_today == dateStr)
        {
            e.Cell.CssClass = "today";
        }
        else if (SelectedDate.Value == dateStr)
        {
            e.Cell.CssClass = "appbody";
        }
        e.Cell.Attributes["onclick"] = string.Format("ShowAppointments('{0:d}')", e.Day.Date);
    }

    protected void ShowAppButton_Click(object sender, EventArgs e)
    {
        DateTime showDate;
        if (!DateTime.TryParse(SelectedDate.Value, out showDate))
        {
            showDate = WebUser.CurrentUser.GetLocalToday();
        }
        LoadDaily(showDate);
    }

    private void LoadDaily(DateTime showDate)
    {
        McCalendar calendar = new McCalendar(_calendarId);
        DateTime beginDate = showDate;
        DateTime endDate = beginDate.AddDays(1);
        Appointment[] appointments = calendar.GetAppointments(beginDate, endDate);

        AppListView.DataSource = appointments;
        AppListView.DataBind();
        CalendarName.Text = calendar.Name;
    }

    protected string GetAppTimeStr(int type, DateTime beginTime, DateTime endTime, bool isRecurrent)
    {
        string retval;
        TimeSpan ts = endTime.Subtract(beginTime);
        if (ts.TotalHours > 24)
        {
            retval = Resources.Calendar.SeveralDays;
        }
        else if (((Tabs.Appointment.AppointmentType)type & Tabs.Appointment.AppointmentType.AllDay) > 0)
        {
            retval = Resources.Calendar.AllDay2;
        }
        else
        {
            retval = beginTime.ToString("tt h:mm");
        }
        if (isRecurrent) retval += " <span class=\"fa-solid fa-rotate-right\"></span>";
        return retval;
    }

    protected string GetSubject(string subject, string place)
    {
        if (place.Length > 0)
            return Server.HtmlEncode(string.Format("{0} ({1})", subject, place));
        else
            return Server.HtmlEncode(subject);
    }

    protected string GetClickEventFunction(Appointment app)
    {
        return string.Format("OpenAppointment(\"{0}\", {1}, \"{2}\", \"{3:s}\");", app.ID, app.IsRecurrent ? "true" : "false", app.RecurrenceID, app.BeginTime);
    }
}