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

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

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

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

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

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

        public async Task<IActionResult> AddOrEdit(int id = 0)
        {

         //   ViewBag.Plants = _context.Plants;

            if (id == 0)
            {
                var item = new Project();
                item.Plants = _context.Plants.ToList();

                return View(item);
            }
            else
            {
                var item = await _context.Projects.FindAsync(id);
                

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

                item.Plants = _context.Plants.ToList();
                return View(item);
            }
        }

        [HttpPost]
        //[ValidateAntiForgeryToken]
        public async Task<IActionResult> AddOrEdit(int id, Project item)
        {
            ModelState.Remove("Plants");
            ModelState.Remove("Plant");

            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", _context.Projects.ToList()) });
            }
            else
            {
                var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));
            }            
            return Json(new { isValid = false, html = Helper.RenderRazorViewToString(this, "AddOrEdit", item) });
        }

        //if (ModelState.IsValid)
        //{
        //    if (project.Id == 0)
        //    {
        //        var highestPrjNo = 0;
        //        int prjYear = 0;
        //        int prjNo = 0;

        //        if (_context.Projects.Count() > 0)
        //        {
        //            highestPrjNo = _context.Projects.Max(x => x.No);
        //            prjYear = highestPrjNo;

        //            // Projekt Jahr freistellen
        //            while (prjYear >= 100)
        //                prjYear /= 10;

        //            // Laufende Nr. des Jahres freistellen
        //            prjNo = highestPrjNo >= 1000 ? highestPrjNo % 1000 : highestPrjNo;
        //        }

        //        // Neue Projekt Nummer berechnen
        //        if (prjYear == int.Parse(DateTime.Now.ToString("yy")))
        //        {
        //            project.No = prjYear * 1000 + prjNo + 1;
        //        }
        //        else
        //        {
        //            project.No = int.Parse(DateTime.Now.ToString("yy")) * 1000 + 1;
        //        }

        //        _context.Projects.Add(project);
        //    }
        //    else
        //    {
        //        _context.Projects.Update(project);

        //    }


        //    await _context.SaveChangesAsync();
        //}
        //return RedirectToAction("Index");


    

        public async Task<IActionResult> DeleteProject(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var project = await _context.Projects.FirstOrDefaultAsync(x => x.Id == id);

            if (project == null)
            {
                return NotFound();
            }

            _context.Remove(project);
            _context.SaveChanges();

            return RedirectToAction("Index");
        }
    }
}
