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 IActionResult Index()
        {

            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);

            return View();
        }

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

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

     


    }
}