using Microsoft.AspNetCore.Mvc;
using FSI.BT.IR.Organization.Db.Services;

namespace FSI.BT.IR.Organization.Web.Controllers;

public class HomeController : Controller
{

    private readonly IOrganizationService _service;

    public HomeController(IOrganizationService service)
    {
        _service = service;
    }

    public async Task<IActionResult> IndexAsync()
    {
        Task<List<Organization.Db.Models.Organization>> data = _service.GetDatasAsync();

        return View(await data);
    }

    public async Task<IActionResult> AddOrEditAsync(int id = 0)
    {
        if (id == 0)
        {
            var item = new Organization.Db.Models.Organization();
            item.Parents = (await _service.GetDatasAsync()).OrderBy(x => x.Name).ToList();
            item.Parents.Add(new Organization.Db.Models.Organization());

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

            return View(item);
        }
        else
        {
            var item = await _service.GetDataByIdAsync(id);

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

            item.Parents = await _service.GetDatasAsync();
            item.Parents.Add(new Organization.Db.Models.Organization()); // neue & leere Organisation einfügen
            item.Parents.Remove(item); // eigene 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.Db.Models.Organization item)
    {
        ModelState.Remove(nameof(item.Parent));
        ModelState.Remove(nameof(item.Parents));
        ModelState.Remove(nameof(item.FullShortName));

        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
                    await _service.AddAsync(item);
                }
                catch (Exception ex)
                {

                }
            }
            else // Update
            {
                try
                {
                    await _service.UpdateAsync(item);
                }
                catch (Exception ex)
                {

                }
            }

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

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

    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmedAsync(int id)
    {
        await _service.SetParentIdNullAsync(id);

        var item = await _service.GetDataByIdAsync(id);
        await _service.RemoveAsync(item);

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


}
