using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Kendo.Mvc.UI;
using Kendo.Mvc.Export;
using Kendo.Mvc.Extensions;
using KendoUIMVC5.Models;
using System.Linq;
using Newtonsoft.Json;
using System.Web;
using Telerik.Documents.SpreadsheetStreaming;
using System.IO;
using Kendo.Mvc;
using Kendo.Mvc.Infrastructure;

namespace KendoUIMVC5.Controllers
{
    public class HomeController : Controller
    {
        public static ICollection<Student> students = new List<Student>();
        [HttpPost]
        public FileStreamResult ExportServer(string model, string data, string filter)
        {
            var columnsData = JsonConvert.DeserializeObject<IList<ExportColumnSettings>>(HttpUtility.UrlDecode(model));
            var filters = FilterDescriptorFactory.Create(filter);
            var filteredData= students.ToDataSourceResult(new DataSourceRequest() { Filters=filters,Page=1}).Data;

            dynamic options = JsonConvert.DeserializeObject(HttpUtility.UrlDecode(data));
            SpreadDocumentFormat exportFormat = options.format.ToString() == "csv" ? exportFormat = SpreadDocumentFormat.Csv : exportFormat = SpreadDocumentFormat.Xlsx;
            Action<ExportCellStyle> cellStyle = new Action<ExportCellStyle>(ChangeCellStyle);
            Action<ExportRowStyle> rowStyle = new Action<ExportRowStyle>(ChangeRowStyle);
            Action<ExportColumnStyle> columnStyle = new Action<ExportColumnStyle>(ChangeColumnStyle);

            string fileName = string.Format("{0}.{1}", options.title, options.format);
            string mimeType = Helpers.GetMimeType(exportFormat);

            Stream exportStream = filteredData.ToXlsxStream(columnsData, (string)options.title.ToString(), cellStyleAction: cellStyle, rowStyleAction: rowStyle, columnStyleAction: columnStyle);

            var fileStreamResult = new FileStreamResult(exportStream, mimeType);
            fileStreamResult.FileDownloadName = fileName;
            fileStreamResult.FileStream.Seek(0, SeekOrigin.Begin);

            return fileStreamResult;
        }
        public HomeController()
        {
            var names = new List<string> { "John", "Jane", "Jeremy", "James" };
            var lastNames = new List<string> { "Hammont", "Clarkson", "May", "Hennethon" };
            var random = new Random();
            if (students.Count == 0)
            {
                for (int i = 1; i < 50; i++)
                {
                    students.Add(new Student
                    {
                        Age = random.Next(1, 20),
                        Birthday = new DateTime(random.Next(1950, 2018), random.Next(1, 12), random.Next(1, 27)),
                        FirstName = names[random.Next(0, 4)],
                        LastName = lastNames[random.Next(0, 4)],
                        Id = i
                    });
                }
            }
        }

        public ActionResult Index()
        {
            return View();
        }


        private void ChangeCellStyle(ExportCellStyle e)
        {
            bool isHeader = e.Row == 0;
            SpreadCellFormat format = new SpreadCellFormat
            {
                ForeColor = isHeader ? SpreadThemableColor.FromRgb(50, 54, 58) : SpreadThemableColor.FromRgb(214, 214, 217),
                IsItalic = true,
                VerticalAlignment = SpreadVerticalAlignment.Center,
                WrapText = true,
                Fill = SpreadPatternFill.CreateSolidFill(isHeader ? new SpreadColor(93, 227, 0) : new SpreadColor(50, 54, 58))
            };
            e.Cell.SetFormat(format);
        }

        private void ChangeRowStyle(ExportRowStyle e)
        {
            e.Row.SetHeightInPixels(e.Index == 0 ? 80 : 30);
        }

        private void ChangeColumnStyle(ExportColumnStyle e)
        {
            double width = e.Name == "Product name" || e.Name == "Category Name" ? 250 : 100;
            e.Column.SetWidthInPixels(width);
        }
        public ActionResult GetStudents([DataSourceRequest] DataSourceRequest request)
        {

            return Json(students.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }

        public ActionResult EditStudent(Student student)
        {
            students.Where(x => x.Id == student.Id).Select(x => student);

            return Json(student);
        }

        public ActionResult CreateStudent(Student student)
        {
            student.Id = students.Count + 1;
            students.Add(student);

            return Json(student);
        }

        public ActionResult DestroyStudent(Student student)
        {
            students.Remove(students.First(x => x.Id == student.Id));

            return Json(student);
        }
    }
}


