using FSI.BT.IR.Plc.Settings.Log.Data;
using FSI.BT.IR.Plc.Settings.Log.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace FSI.BT.IR.Plc.Settings.Log.Controllers
{
    public class OrganizationController : Controller
    {

        private readonly ApplicationDbContext _context;
        private readonly DataManager _dataManager;
        public OrganizationController(ApplicationDbContext context)
        {
            _context = context;
            _dataManager = new(context);
        }

        public async Task<IActionResult> IndexAsync()
        {
            Task<List<Organization>> data = _dataManager.LoadOrganizationsAsync();

            return View(await data);
        }

        public async Task<IActionResult> AddOrEditAsync(int id = 0)
        {
            if (id == 0)
            {
                var item = new Organization();
                item.Parents = _context.Organizations.OrderBy(x => x.Name).ToList();
                item.Parents.Add(new Organization());

                if (item.ParentId == null)
                {
                    item.ParentId = 0;
                }

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

                if (item == null) // kein Fund
                {
                    return NotFound();
                }

                item.Parents = _context.Organizations.ToList();
                item.Parents.Add(new Organization()); // neue & leere Organisation einfügen
                item.Parents.Remove(item); // eingene Organisation entfernen
                item.Parents.OrderBy(x => x.Name); // sortieren

                if (item.ParentId == null)
                {
                    item.ParentId = 0;
                }

                return View(item);
            }
        }

        [HttpPost]
        public async Task<IActionResult> AddOrEditAsync(int id, Organization item)
        {
            ModelState.Remove(nameof(item.Parent));
            ModelState.Remove(nameof(item.Parents));
            ModelState.Remove(nameof(item.FullShortName));

            if (string.IsNullOrEmpty(item.FullShortName))
            {
                item.FullShortName = _dataManager.GetOrganizationFullShortName(_context.Organizations.ToList(), item.ParentId, item.ShortName);
            }

            item.Updated = DateTime.Now; // Zeitstempel für Modifikation 

            if (ModelState.IsValid)
            {

                if (item.ParentId == 0)
                {
                    item.ParentId = null;
                }

                if (id == 0) // Insert
                {
                    try
                    {
                        item.Created = item.Updated; // Zeitstempel für Erstellung
                        _context.Add(item);
                        await _context.SaveChangesAsync();
                    }
                    catch (Exception ex)
                    {

                    }
                }
                else // Update
                {
                    try
                    {
                        _context.Update(item);
                        await _context.SaveChangesAsync();
                    }
                    catch (Exception ex)
                    {

                    }
                }

                return Json(new { isValid = true, html = Helper.RenderRazorViewToString(this, "_ViewAll", await _dataManager.LoadOrganizationsAsync()) });
            }
            else
            {
                var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));
            }

            item.Parents.Add(new Organization());
            return Json(new { isValid = false, html = Helper.RenderRazorViewToString(this, "AddOrEdit", item) });
        }

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmedAsync(int id)
        {
            await _context.Organizations
                .Where(x => x.ParentId == id)
                .ForEachAsync(x => x.ParentId = null); // Parent Ids auf null sezten

            var item = await _context.Organizations.FindAsync(id);
            _context.Organizations.Remove(item);

            await _context.SaveChangesAsync();

            return Json(new { html = Helper.RenderRazorViewToString(this, "_ViewAll", await _dataManager.LoadOrganizationsAsync()) });
        }


    }
}
