using Microsoft.AspNetCore.Mvc;
using Berufsschule_HAM.Models;
using Berufsschule_HAM.Services;
using Berufsschule_HAM.Helpers;
using System.Text.Json;
using Novell.Directory.Ldap;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.ModelBinding;

[Authorize]
[Route("[controller]")]
public class AssetsController : Controller
{
    private readonly LdapService _ldap;
    private readonly ILogger<AssetsController> _logger;

    public AssetsController(LdapService ldap, ILogger<AssetsController> logger)
    {
        _ldap = ldap ?? throw new ArgumentNullException(nameof(ldap));
        _logger = logger;
    }

    [Authorize(Roles = "CanManageAssets,CanInventorize")]
    [HttpGet("Get")]
    public async Task<AssetsGetResponseModel> GetAllAssetModelAsync(string Cn)
    {
        AssetsGetResponseModel result;
        try
        {
            var assetList = await _ldap.ListDeviceAsync(Cn);
            result = new AssetsGetResponseModel(successful: true, assetModel: assetList);
            if (result.AssetsModel is not null)
            {
                result.AssetsModel.Owner = result.AssetsModel?.Owner?.Replace("uid=", "");            
            }
        }
        catch (Exception e)
        {
            result = new AssetsGetResponseModel(successful: false, exception: e.Message);
        }
        
        return result;
    }

    [Authorize(Roles = "CanManageAssets")]
    [HttpGet("GetAll")]
    public async Task<AssetsGetAllResponseModel> GetAllAssetModelAsync()
    {
        AssetsGetAllResponseModel result;
        try
        {
            var assetList = await _ldap.ListDeviceAsync();
            result = new AssetsGetAllResponseModel(successful: true, assetsModel: assetList);
            result.AssetsModel = result.AssetsModel?.Select(asset =>
            {
                asset.Owner = asset.Owner?.Replace("uid=", "");
                return asset;
            });
        }
        catch (Exception e)
        {
            result = new AssetsGetAllResponseModel(successful: false, exception: e.Message);
        }
        
        return result;
    }

    [Authorize(Roles = "CanManageAssets")]
    [HttpPost("Create")]
    public async Task<AssetsCreateResponseModel> Create([FromBody]AssetsCreateRequestModel assetModel)
    {
        string? assetId;
        AssetsCreateResponseModel result;
        if (assetModel is null)
        {
            result = new AssetsCreateResponseModel(
                successful: false,
                exception: "Unable to create an asset because the AssetsCreateRequestModel is null.");

            return result;
        }

        try
        {
            LdapAttributeSet attributeSet =
            [
                new LdapAttribute("objectClass", ["top", "device", "extensibleObject"]),
            ];
            assetId = await _ldap.GetAssetCounterAndIncrementAsync();
            attributeSet.Add(new LdapAttribute("cn", assetId));
            if (assetModel.SerialNumber != null)
            {
                attributeSet.Add(new LdapAttribute("serialNumber", assetModel.SerialNumber));
            }
            if (assetModel.Location != null)
            {
                attributeSet.Add(new LdapAttribute("l", assetModel.Location));
            }
            if (assetModel.Owner != null)
            {
                var ownerDn = $"uid={assetModel.Owner}";
                attributeSet.Add(new LdapAttribute("owner", ownerDn));
            }
            if (assetModel.Name != null)
            {
                attributeSet.Add(new LdapAttribute("name", assetModel.Name));
            }
            assetModel.Description ??= new();
            assetModel.Description.Inventory = GenerateInventory();
            attributeSet.Add(new LdapAttribute("description", JsonSerializer.Serialize(assetModel.Description)));

            await _ldap.CreateAsset(attributeSet);
            result = new AssetsCreateResponseModel(successful: true, assetId);
        }
        catch (Exception e)
        {
            result = new AssetsCreateResponseModel(successful: false, exception: e.Message);
        }

        return result;
    }

    [Authorize(Roles = "CanManageAssets")]
    [HttpDelete("Delete")]
    public async Task<AssetsDeleteResponseModel> Delete([BindRequired] string cn)
    {        
        AssetsDeleteResponseModel response;
        return await Task.Run(async () =>
        {
            if (cn is null)
            {
                response = new AssetsDeleteResponseModel(successful: false, exception: "Cn was not provided.");
                return response;
            }

            try
            {
                await _ldap.DeleteAssetAsync(cn);
                response = new AssetsDeleteResponseModel(true);
            }
            catch (Exception e)
            {
                response = new AssetsDeleteResponseModel(successful: false, exception: e.Message);
            }

            return response;
        });
    }

    [Authorize(Roles = "CanManageAssets,CanInventorize")]
    [HttpPatch("Update")]
    public async Task<AssetsUpdateResponseModel> Update([FromBody] AssetsModifyRequestModel requestModel)
    {
        AssetsUpdateResponseModel result;
        if (requestModel is null)
        {
            result = new AssetsUpdateResponseModel(
                successful: false,
                exception: "Unable to update an asset because the AssetsModifyRequestModel is null");

            return result;
        }

        try
        {
            var cn = requestModel.Cn;
            if (requestModel.NewCn is not null)
            {
                await _ldap.UpdateAsset(cn, "cn", requestModel.NewCn);
                cn = requestModel.NewCn;
            }
            if (requestModel.Location is not null)
            {
                await _ldap.UpdateAsset(cn, "l", requestModel.Location);
            }
            if (requestModel.Name is not null)
            {
                await _ldap.UpdateAsset(cn, "name", requestModel.Name);
            }
            if (requestModel.Owner is not null)
            {
                await _ldap.UpdateAsset(cn, "owner", $"uid={requestModel.Owner}");
            }
            if (requestModel.SerialNumber is not null)
            {
                await _ldap.UpdateAsset(cn, "serialNumber", requestModel.SerialNumber);
            }
            AssetModel asset = await _ldap.ListDeviceAsync(requestModel.Cn);
            asset.Description ??= new();
            if (requestModel.Description is not null)
            {
                AssetInventory? tempInventory = asset.Description.Inventory;
                AttributesHelper.UpdateNonNullProperties(requestModel.Description, asset.Description);
                asset.Description.Inventory = tempInventory;
                await _ldap.UpdateAsset(cn, "description", JsonSerializer.Serialize(asset.Description));
            }
            if (requestModel.UpdateInventory)
            {
                asset.Description.Inventory = GenerateInventory();
                await _ldap.UpdateAsset(cn, "description", JsonSerializer.Serialize(asset.Description));
            }

            result = new AssetsUpdateResponseModel(successful: true);
        }
        catch (Exception e)
        {
            result = new AssetsUpdateResponseModel(successful: false, exception: e.Message);
        }

        return result;
    }
    
    private AssetInventory GenerateInventory()
    {
        string? userName = User.Identity?.Name ?? "Unknown";
        return new() { Date = DateTime.UtcNow.ToString("o"), PersonUid = userName };
    }
}