using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ManipulateWebGridDemo.Controllers
{
    public class HomeController : Controller
    {
        public static List<Models.Student>    Students = new List<Models.Student>()
            {
                new Models.Student { 
                    ID = 1, 
                    Name = "Adam Worth", 
                    email = "adam.worthh@abc.edu", 
                },
                new Models.Student { 
                    ID = 2, 
                    Name = "John Doe",  
                    email = "john.doe@abc.edu", 
                },
                new Models.Student { 
                    ID = 3, 
                    Name = "Gorge Klene", 
                    email = "gorge.klene@abc.edu", 
                }
            };
        public ActionResult Index()
        {
            return View(Students );
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        [HttpPost]
        public JsonResult InsertData(Models.Student inStudent)
        {
            String result = String.Empty;

            Models.Student dup = Students.Find(p => p.ID == inStudent.ID);

            if (dup == null)
            {
                Students.Add(inStudent);
                result = "1";
            }
            else
            {
                result = "0";
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult SaveData(Models.Student student)
        {
            int index = 0;
            String result = String.Empty;

            index = Students.FindIndex(p => p.ID == student.ID);
            if (index >= 0)
            {
                Students[index] = student;
                result = "1";
            }
            else
                result = "0";

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult DeleteData(Models.Student student)
        {
            String result = String.Empty;

            Models.Student s = Students.Find(p => p.ID == student.ID);
            if (s != null)
            {
                Students.Remove(s);
                result = "1";
            }
            else
                result = "0";

            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}
