using FSI.Prj.Mgt.Data;
using FSI.Prj.Mgt.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using X.PagedList;

namespace FSI.Prj.Mgt.Controllers
{
    public class PlantController : Controller
    {
        private readonly ApplicationDbContext _context;

        public PlantController(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<IActionResult> Index(string searchString, int? page)
        {
            IQueryable<Plant> items = _context.Plants;

            if (!string.IsNullOrEmpty(searchString))
            {
                items = items.Where(x => x.Name!.ToString().Contains(searchString));
            }

            return View(await items.ToPagedListAsync(page ?? 1, 10));
        }

        public async Task<IActionResult> AddOrEdit(int id = 0)
        {
            if (id == 0)
            {
                return View(new Plant());
            }
            else
            {
                var item = await _context.Plants.FindAsync(id);

                if (item == null)
                {
                    return NotFound();
                }
                return View(item);
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> AddOrEdit(int id, Plant item)
        {
            if (ModelState.IsValid)
            {

                if (id == 0) // Insert
                {
                    _context.Add(item);
                    await _context.SaveChangesAsync();
                }
                else // Update
                {
                    try
                    {
                        _context.Update(item);
                        await _context.SaveChangesAsync();
                    }
                    catch (DbUpdateConcurrencyException)
                    {

                    }
                }

                return Json(new { isValid = true, html = Helper.RenderRazorViewToString(this, "_ViewAll", await ((IQueryable<Plant>)_context.Plants).ToPagedListAsync(1, 10)) });
            }
            else
            {
                var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));
            }
            return Json(new { isValid = false, html = Helper.RenderRazorViewToString(this, "AddOrEdit", item) });
        }
    }
}
