using FSI.Prj.Mgt.Data;
using FSI.Prj.Mgt.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Newtonsoft.Json;
using X.PagedList;

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

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

        public async Task<IActionResult> Index(string searchString, int? page)
        {

            IQueryable<Organization> items = _context.Organizations.Include(x => x.Parent);


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

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




            List<TreeViewNode> nodes = new();

            // Loop and add the Parent Nodes
            foreach (Organization organization in _context.Organizations)
            {
                if (organization.ParentId == null)
                {
                    nodes.Add(new TreeViewNode
                    {
                        id = organization.Id.ToString(),
                        parent = "#",
                        text = organization.Name,
                    });
                }
                else
                {
                    nodes.Add(new TreeViewNode
                    {
                        id = organization.Id.ToString(),
                        parent = organization.ParentId.ToString(),
                        text = organization.Name,
                    });
                }
            }
            ViewBag.Json = JsonConvert.SerializeObject(nodes);
            
        }

        [HttpPost]
        public IActionResult Index (string selectedItems)
        {
            if (selectedItems != null)
            {
                List<TreeViewNode> items = JsonConvert.DeserializeObject<List<TreeViewNode>>(selectedItems);
            }

            return RedirectToAction("Index", "Organization");
        }

     


    }
}