using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Text;
using DayPilot.Utils;
using DayPilot.Web.Ui.Enums;
using DayPilot.Web.Ui.Events;
using DayPilot.Web.Ui.Events.Calendar;
using DayPilot.Web.Ui.Events.Bubble;
using DayPilot.Web.Ui.Recurrence;

public partial class _Default : System.Web.UI.Page 
{
    private DayPilotDataClassesDataContext db;

    protected void Page_Load(object sender, EventArgs e)
    {
        db = new DayPilotDataClassesDataContext();

        if (!IsPostBack)
        {
            DayPilotCalendar1.StartDate = DayPilot.Utils.Week.FirstDayOfWeek();
            LoadEvents();
            DataBind();
        }
    }

    private void LoadEvents()
    {
        DateTime start = DayPilotCalendar1.StartDate;
        DateTime end = DayPilotCalendar1.StartDate.AddDays(DayPilotCalendar1.Days);

        DayPilotCalendar1.DataSource = LoadEventsFromRange(start,end);
        DayPilotNavigator1.DataSource = LoadEventsFromRange(DayPilotNavigator1.VisibleStart,
                                                            DayPilotNavigator1.VisibleEnd);
                
    }

    private IQueryable<Event> LoadEventsFromRange(DateTime start, DateTime end)
    {
        return from ev in db.Events where !(ev.eventend <= start || ev.eventstart >= end) || (ev.recurrence != null && ev.eventstart < end) select ev;
    }


    protected void DayPilotCalendar1_EventMove(object sender, EventMoveEventArgs e)
    {
        Event target = findEvent(e.Value);

        // recurrent event but no exception
        if (e.Recurrent && !e.RecurrentException)
        {
            int masterId = Convert.ToInt32(e.RecurrentMasterId);
            Event master = (from ev in db.Events where ev.id == masterId select ev).FirstOrDefault();

            Event created = new Event
                               {
                                   name = master.name,
                                   eventstart = e.NewStart,
                                   eventend = e.NewEnd,
                                   recurrence = RecurrenceRule.EncodeExceptionModified(e.RecurrentMasterId, e.OldStart)
                               };

            db.Events.InsertOnSubmit(created);
            db.SubmitChanges();

        }
        // recurrent exception or regular event
        else if (target != null)
        {
            target.eventstart = e.NewStart;
            target.eventend = e.NewEnd;
            db.SubmitChanges();
        }

        LoadEvents();
        DayPilotCalendar1.DataBind();

        Hashtable ht = new Hashtable();
        ht["message"] = "Event moved.";
        ht["id"] = e.Value;

        DayPilotCalendar1.Update(ht);
    }

    private Event findEvent(string eventId)
    {
        int eid = Convert.ToInt32(eventId);
        return (from ev in db.Events where ev.id == eid select ev).FirstOrDefault();
    }

    protected void DayPilotCalendar1_EventMenuClick(object sender, EventMenuClickEventArgs e)
    {
        if (e.Command == "Delete")
        {
            Event target = findEvent(e.Value);

            if (target != null)
            {
                db.Events.DeleteOnSubmit(target);
                db.SubmitChanges();
            }

            LoadEvents();
            DayPilotCalendar1.DataBind();
            DayPilotCalendar1.Update();
        }
    }
    protected void DayPilotCalendar1_TimeRangeSelected(object sender, TimeRangeSelectedEventArgs e)
    {
        Event created = new Event
        {
            name = "New Event",
            eventstart = e.Start,
            eventend = e.End
        };

        db.Events.InsertOnSubmit(created);
        db.SubmitChanges();

        LoadEvents();
        DayPilotCalendar1.DataBind();
        DayPilotCalendar1.Update("New event created.");
    }

    protected void DayPilotCalendar1_EventResize(object sender, EventResizeEventArgs e)
    {
        //var db = new DayPilotDataClassesDataContext();
        Event target = findEvent(e.Value);

        if (e.Recurrent && !e.RecurrentException)
        {
            Event master = findEvent(e.RecurrentMasterId);
            
            Event created = new Event
            {
                name = master.name,
                eventstart = e.NewStart,
                eventend = e.NewEnd,
                recurrence = RecurrenceRule.EncodeExceptionModified(e.RecurrentMasterId, e.OldStart)
            };

            db.Events.InsertOnSubmit(created);
            db.SubmitChanges();

        }
        else if (target != null)
        {
            target.eventstart = e.NewStart;
            target.eventend = e.NewEnd;
            db.SubmitChanges();
        }


        LoadEvents();
        DayPilotCalendar1.DataBind();
        DayPilotCalendar1.Update("Event resized");
    }

    protected void DayPilotCalendar1_EventEdit(object sender, EventEditEventArgs e)
    {
        Event target = findEvent(e.Value);

        if (target != null)
        {
            target.name = e.NewText;
            db.SubmitChanges();
        }

        LoadEvents();
        DayPilotCalendar1.DataBind();
        DayPilotCalendar1.Update("Event text changed.");
    }
    protected void DayPilotCalendar1_BeforeEventRender(object sender, BeforeEventRenderEventArgs e)
    {
    }


    protected void DayPilotCalendar1_EventDelete(object sender, EventDeleteEventArgs e)
    {

        Event target = findEvent(e.Value);

        if (e.Recurrent && !e.RecurrentException)
        {
            Event created = new Event
                               {
                                   eventstart = e.Start,
                                   eventend = e.End,
                                   recurrence = RecurrenceRule.EncodeExceptionDeleted(e.RecurrentMasterId, e.Start)
                               };

            db.Events.InsertOnSubmit(created);
            db.SubmitChanges();
        }
        else if (target != null)
        {
            db.Events.DeleteOnSubmit(target);
            db.SubmitChanges();
        }

        LoadEvents();
        DayPilotCalendar1.DataBind();
        DayPilotCalendar1.Update("Event deleted.");
    }

    protected void DayPilotCalendar1_EventSelect(object sender, DayPilotEventArgs e)
    {
        DayPilotCalendar1.Update();
    }


    protected void DayPilotCalendar1_BeforeHeaderRender(object sender, BeforeHeaderRenderEventArgs e)
    {
        if (e.IsCorner)
        {
            e.InnerHTML = String.Format("<div style='padding:2px; text-align:center; font-weight: bold;'>{0}</div>", DayPilotCalendar1.StartDate.Year);
        }
    }

    protected void DayPilotBubble1_RenderContent(object sender, RenderEventArgs e)
    {
        if (e is RenderEventBubbleEventArgs)
        {
            RenderEventBubbleEventArgs re = e as RenderEventBubbleEventArgs;

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("<b>{0}</b><br />", re.Text);
            sb.AppendFormat("Start: {0}<br />", re.Start);
            sb.AppendFormat("End: {0}<br />", re.End);
            sb.AppendFormat("<br />");
            sb.AppendFormat("<b>Double-click the event to enter inline edit mode.</b>");

            re.InnerHTML = sb.ToString();
        }
        else if (e is RenderTimeBubbleEventArgs)
        {
            RenderTimeBubbleEventArgs re = e as RenderTimeBubbleEventArgs;
            e.InnerHTML = "<b>Time header details</b><br />From:" + re.Start + "<br />To: " + re.End;
        }
        else if (e is RenderCellBubbleEventArgs)
        {
            RenderCellBubbleEventArgs re = e as RenderCellBubbleEventArgs;
            e.InnerHTML = "<b>Cell details</b><br />Column:" + re.ResourceId + "<br />From:" + re.Start + "<br />To: " + re.End;
        }
    }


    protected void DayPilotCalendar1_Command(object sender, CommandEventArgs e)
    {
        switch (e.Command)
        {
            case "previous":
                DayPilotCalendar1.StartDate = DayPilotCalendar1.StartDate.AddDays(-7);
                LoadEvents();
                DayPilotCalendar1.DataBind();
                DayPilotCalendar1.Update(CallBackUpdateType.Full);
                break;
            case "navigate":
                DateTime start = (DateTime)e.Data["start"];
                DateTime end = (DateTime)e.Data["end"];

                DayPilotCalendar1.StartDate = start;

                LoadEvents();
                DayPilotCalendar1.DataBind();
                DayPilotCalendar1.Update(CallBackUpdateType.Full);
                break;
            case "refresh":
                LoadEvents();
                DayPilotCalendar1.DataBind();
                DayPilotCalendar1.Update();
                break;
        }


    }
    protected void DayPilotNavigator1_VisibleRangeChanged(object sender, EventArgs e)
    {
        LoadEvents();
        DayPilotNavigator1.DataBind();
    }

    protected void DayPilotCalendar1_BeforeCellRender(object sender, BeforeCellRenderEventArgs e)
    {
    }

    protected void DayPilotCalendar1_HeaderClick(object sender, HeaderClickEventArgs e)
    {
    }

}
