using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using QuickForm;
using Newtonsoft.Json;
using ScaffoldingExample.Helpers;
using ScaffoldingExample.Models;

namespace ScaffoldingExample.Controllers
{   

    public class ComputerController : Controller
    {
        const string ControllerName = "Computer";
        private Model1Container db = new Model1Container();
        private string DtVarIdName = QuickFormModel.DtVarIdName(ControllerName);

        //
        // GET: /Computer/

        public ViewResult Index()
        {
			int DTListDisplayLength = QuickFormProject.DTListDisplayLength;
			QuickFormModel model = QuickFormProject.Data["Computer"].forIndexClassifier(DTListDisplayLength);
            
            //Выбранная строка в списке с учетом фильтра по вопросам
            var filteredData = GetDataWithFilter().ToList();
            DataTableHelper.InitDtVarIdName(Session, DtVarIdName,
                () => (filteredData.Count() > 0),
                id => (filteredData.Count(x => x.Id == id) > 0),
                () =>
                {
                        int Result = filteredData.Min(x => x.Id);
                        return Result;
                }
                );

            //Возврат данных в форму
            return View(model);
        }

        /// <summary>
        /// Получение выборки с учетом возможного фильтра
        /// </summary>
        public IQueryable<Computer> GetDataWithFilter()
        {
            var query = from x in db.Computers
                        select x;

            return query;
        }


		public string ListData()
        {
            var data = new DtJson<DtData>();
            var query = GetDataWithFilter();
            foreach(var x in query)
            {
                DtData temp = new DtData()
                {
                    id = x.Id.ToString(),
                    text = x.ComputerName
                };
                data.Add(temp);
            }
            return JsonConvert.SerializeObject(data);
        }

        //
        // GET: /Computer/Create

        public ActionResult Create(int? dtid)
        {
            if (dtid.HasValue)
            {
                //Установка  номера текущей строки в DataTable
                Session.Add(DtVarIdName, dtid.Value);
            }

			ViewBag.ProcessorId = new SelectList(db.Processors.WithOrder(), "Id", "ProcessorName");
            Computer currentData = new Computer();
            return View(currentData);
        } 

        //
        // POST: /Computer/Create

        [HttpPost]
        public ActionResult Create(Computer computer)
        {
            if (
                db.Computers.Any(x => x.ComputerName.Trim().ToUpper().Equals(computer.ComputerName.Trim().ToUpper()))
                )
            {
                ModelState.AddModelError("ComputerName", QuickFormProject.ErrorText_RepeatValue);
            }           

            if (ModelState.IsValid)
            {
                db.Computers.Add(computer);
                db.SaveChanges();

                //Установка  номера текущей строки в DataTable
                Session.Add(DtVarIdName, computer.Id);

                return RedirectToAction("Index");  
            }

			ViewBag.ProcessorId = new SelectList(db.Processors.WithOrder(), "Id", "ProcessorName", computer.ProcessorId);
			return View(computer);
        }
        
        //
        // GET: /Computer/Edit/5
 
        public ActionResult Edit(int id)
        {
            Computer computer = db.Computers.Single(x => x.Id == id);
            if (computer == null)
            {
                return HttpNotFound();
            }

            //Установка  номера текущей строки в DataTable
            Session.Add(DtVarIdName, id);

			ViewBag.ProcessorId = new SelectList(db.Processors.WithOrder(), "Id", "ProcessorName", computer.ProcessorId);
			return View(computer);
        }

        //
        // POST: /Computer/Edit/5

        [HttpPost]
        public ActionResult Edit(Computer computer)
        {
            if (
                db.Computers.Any(x => x.ComputerName.Trim().ToUpper().Equals(computer.ComputerName.Trim().ToUpper())
									&& x.Id != computer.Id)
                )
            {
                ModelState.AddModelError("ComputerName", QuickFormProject.ErrorText_RepeatValue);
            }           
			
			if (ModelState.IsValid)
            {
                db.Entry(computer).State = EntityState.Modified;
                db.SaveChanges();

                //Установка  номера текущей строки в DataTable
                Session.Add(DtVarIdName, computer.Id);

                return RedirectToAction("Index");
            }

			ViewBag.ProcessorId = new SelectList(db.Processors.WithOrder(), "Id", "ProcessorName", computer.ProcessorId);
			return View(computer);
        }

        //
        // GET: /Computer/Delete/5
 
        public ActionResult Delete(int id)
        {
            Computer computer = db.Computers.Single(x => x.Id == id);
            if (computer == null)
            {
                return HttpNotFound();
            }

            //Установка  номера текущей строки в DataTable
            Session.Add(DtVarIdName, id);

			return View(computer);
        }

        //
        // POST: /Computer/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Computer computer = db.Computers.Single(x => x.Id == id);

            //Удаление объекта
            db.Computers.Remove(computer);
            db.SaveChanges();

            //Установка  номера текущей строки в DataTable
            Session.Add(DtVarIdName, null);

            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing) {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}