using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TelerikMvcApp20.Models;

namespace TelerikMvcApp20.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        private List<SchedulerEventModel> appointments = new List<SchedulerEventModel> {
            new SchedulerEventModel {
                TaskID = 0,
                Description = "Interview Description",
                Title = "Interview",
                Start = new DateTime(2019,10,29,16,00,00, DateTimeKind.Utc),
                End= new DateTime(2019,10,29,19,00,00, DateTimeKind.Utc),
            },
            new SchedulerEventModel {
                TaskID = 1,
                Description = "Meeting Description",
                Title = "Meeting",
                Start = new DateTime(2019,10,29,16,00,00, DateTimeKind.Utc),
                End= new DateTime(2019,10,29,16,30,00, DateTimeKind.Utc),
                RecurrenceRule = "FREQ=DAILY;COUNT=10"
            }
        };

        public JsonResult Read([DataSourceRequest] DataSourceRequest request)
        {
            return Json(appointments.ToDataSourceResult(request));
        }

        public virtual JsonResult Delete([DataSourceRequest] DataSourceRequest request, SchedulerEventModel task)
        {
            if (ModelState.IsValid)
            {
                appointments.Remove(appointments.Where(x => x.TaskID == task.TaskID).FirstOrDefault());
            }

            return Json(new[] { task }.ToDataSourceResult(request, ModelState));
        }

        public virtual JsonResult Create([DataSourceRequest] DataSourceRequest request, SchedulerEventModel task)
        {
            if (ModelState.IsValid)
            {
                task.TaskID = ++appointments.LastOrDefault().TaskID;
                appointments.Add(task);
            }

            return Json(new[] { task }.ToDataSourceResult(request, ModelState));
        }

        public virtual JsonResult Update([DataSourceRequest] DataSourceRequest request, SchedulerEventModel task)
        {
            if (ModelState.IsValid)
            {
                var appointmentToUpdate = appointments.Where(x => x.TaskID == task.TaskID).FirstOrDefault();
                if (appointmentToUpdate != null)
                {
                    appointmentToUpdate = task;
                }
            }

            return Json(new[] { task }.ToDataSourceResult(request, ModelState));
        }
    }
}
