using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using FlexGridIntro.Models;
using C1.Web.Mvc;
using C1.Web.Mvc.Serialization;
using System.Text.Json.Serialization;
using Newtonsoft.Json;

//using C1.JsonNet;

namespace FlexGridIntro.Controllers
{
    public class Organization
    {
        public string Name { get; set; }
        public int ID { get; set; }
        public List<Person> People { get; set; }
    }
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        public static List<Person> Persons = SampleData.GetData(100).ToList();
        public static List<ProductSales> ProductSales = SampleData.GetProductSales().ToList();
        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }
        public IActionResult Index()
        {
            
            return View(new Organization() { ID=2,Name="Andy",People=Persons });
        }

        [HttpPost]
        public JsonResult UpdateEditedRecord(Person person)
        {
            person.Sales *= 10;
            person.Downloads *= 12;
            person.First += " Server";
            return new JsonResult(person);
        }
        

        [HttpPost]
        public JsonResult UpdatePastedRecord(string people)
        {
            var data = JsonConvert.DeserializeObject<List<Person>>(people).ToList<Person>();
            for (int i = 0; i < data.Count; i++)
            {
                data[i].Sales *= 10;
                data[i].Downloads *= 12;
                data[i].First += " Server";
            }
            return new JsonResult(data);
        }

        [HttpGet]
        public JsonResult GetData()
        {
            return new JsonResult(Persons);
        }

        [HttpGet]
        public JsonResult GridReadOrder(int ID,string First)
        {
            var sales= ProductSales.Where(o => { return o.ID == ID && o.First==First; });
            return Json(sales);   ;
        }
       
        [HttpPut] 
        public JsonResult UpdateDetailGridRecords(int ID,string First, ProductSales sales)
        {
            //code to update
            var index = ProductSales.FindIndex(s => { return s.ID == ID && s.First == First && s.Batch == sales.Batch; });
            ProductSales[index] = sales;
            return new JsonResult(sales);
        }
        [HttpPost]
        public JsonResult AddDetailGridRecords(int ID, string First, ProductSales sales)
        {
            //code to add
            var count = ProductSales.Count;
            sales.Batch = "PRD" + count.ToString();
            ProductSales.Add(sales);
            return new JsonResult(sales);
        }
        [HttpDelete]
        public JsonResult DeleteDetailGridRecords(int ID, string First, string Batch)
        {
            var index = ProductSales.FindIndex(s => { return s.ID == ID && s.First == First && s.Batch == Batch; });
            ProductSales.RemoveAt(index);
            return new JsonResult(ProductSales);
        }
        public ActionResult GridEditOrder(int ID,string First, [C1JsonRequest]CollectionViewEditRequest<ProductSales> requestData)
        {
            var sales = ProductSales.Where(o => { return o.ID == ID && o.First == First; });
            return this.C1Json(CollectionViewHelper.Edit<ProductSales>(requestData, item =>
            {
                string error = string.Empty;
                bool success = true;
                try
                {
                    var index = ProductSales.FindIndex(x => x.Batch== item.Batch);
                    ProductSales[index] = item;
                }
                catch (Exception e)
                {
                    error = e.Message;
                    success = false;
                }
                return new CollectionViewItemResult<ProductSales>
                {
                    Error = error,
                    Success = success && ModelState.IsValid,
                    Data = item
                };
            }, () => ProductSales.Where(o=>o.ID==ID).ToList<ProductSales>()));
        }
        public IActionResult Privacy()
        {
            return View();
        }
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

    }
}
