using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web.Http;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;
using WebMail.Model;
using Telerik.Web.UI;

public class CalendarController : ApiController
{
    private JavaScriptSerializer _serializer;
    private SchedulerProviderBase _provider;
    private WebServiceAppointmentController _controller;

    public CalendarController() : base()
    { 
    }

    private JavaScriptSerializer JavaScriptSerializer
    {
        get
        {
            if (_serializer == null)
            {
                _serializer = new JavaScriptSerializer();
            }

            return _serializer;
        }
    }
    private SchedulerProviderBase Provider
    {
        get
        {
            if (_provider == null)
            {
                _provider = new EntitySchedulerProvider();
            }

            return _provider;
        }
    }
    private WebServiceAppointmentController Controller
    {
        get
        {
            if (_controller == null)
            {
                _controller = new WebServiceAppointmentController(Provider);
            }

            return _controller;
        }
    }

    [HttpGet]
    [Route("api/calendar/GetAppointments")]
    public IEnumerable<AppointmentData> GetAppointments(string schedulerInfo)
    {
        return Controller.GetAppointments(JavaScriptSerializer.Deserialize<MySchedulerInfo>(schedulerInfo));
    }

    [HttpPost]
    [Route("api/calendar/InsertAppointment")]
    public IEnumerable<AppointmentData> InsertAppointment(WebApiData data)
    {
        if (string.IsNullOrEmpty(data.AppointmentData.Subject))
        {
            data.AppointmentData.Subject = "New Event";
        }

        return Controller.InsertAppointment(data.SchedulerInfo, data.AppointmentData);
    }

    [HttpPut]
    public IEnumerable<AppointmentData> UpdateAppointment(WebApiData data)
    {

        return Controller.UpdateAppointment(data.SchedulerInfo, data.AppointmentData);
    }

    [HttpPost]
    public IEnumerable<AppointmentData> CreateRecurrenceException(WebApiData data)
    {
        return Controller.CreateRecurrenceException(data.SchedulerInfo, data.RecurrenceExceptionData);
    }

    [HttpDelete]
    public IEnumerable<AppointmentData> RemoveRecurrenceExceptions(WebApiData data)
    {
        return Controller.RemoveRecurrenceExceptions(data.SchedulerInfo, data.MasterAppointmentData);
    }

    [HttpDelete]
    [Route("api/calendar/DeleteAppointment")]
    public IEnumerable<AppointmentData> DeleteAppointment(WebApiData data)
    {
        return Controller.DeleteAppointment(data.SchedulerInfo, data.AppointmentData, data.DeleteSeries);
    }

    [HttpGet]
    [Route("api/calendar/GetResources")]
    public IEnumerable<ResourceData> GetResources(string schedulerInfo)
    {
        var o = new JavaScriptSerializer().Deserialize<MySchedulerInfo>(schedulerInfo);
        return Controller.GetResources(o);
    }

    [HttpPost]
    [Route("api/calendar/search")]
    public SearchBoxData Search([FromBody]JObject context)
    {
        using (var db  = new WebMailContext())
	    {
	        string text = (string)context["context"]["Text"];
            IEnumerable<SearchBoxItemData> filtered = from ev in db.Events
                                                      where ev.Subject.StartsWith(text)
                                                      select new SearchBoxItemData
                                                      {
                                                          Text = ev.Subject,
                                                          Value = ev.ID.ToString()
                                                      };

            SearchBoxData res = new SearchBoxData();
            res.Items = filtered.ToArray();

            return res;
	    }
    }

    [HttpGet]
    [Route("api/calendar/ical")]
    public HttpResponseMessage ICal()
    {
        List<Appointment> appointments = new List<Appointment>();

        using (WebMailContext db = new WebMailContext())
        {
            appointments.AddRange(db.Events.ToList().Select(SchedulerHelper.AppointmentsResolver));
        }
        string content = RadScheduler.ExportToICalendar(appointments);

        var response = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(content)))
        };

        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/calendar");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = "RadSchedulerExport.ics";
        return response;
    }
}
