using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Monitoring.Models.Binders;

public class TableSortModelBinder : IModelBinder
{
	public Task BindModelAsync(ModelBindingContext bindingContext)
	{
		List<TableSort> sortList = [];

		var keys = bindingContext.HttpContext.Request.Query.Keys
			.Where(k => k.StartsWith("sorts["))
			.ToArray();

		if (keys.Length == 0)
		{
			bindingContext.Result = ModelBindingResult.Success(sortList);
			return Task.CompletedTask;
		}

		var groupedKeys = keys.GroupBy(k => k[..(k.IndexOf(']') + 1)]);

		foreach (var group in groupedKeys)
		{
			var groupField = group.FirstOrDefault(k => k.Contains("field"));
			var field = (string?)null;
			if (!string.IsNullOrEmpty(groupField))
			{
				field = bindingContext.HttpContext.Request.Query[groupField].ToString();
			}

			var groupDirection = group.FirstOrDefault(k => k.Contains("direction"));
			var direction = (string?)null;
			if (!string.IsNullOrEmpty(groupDirection))
			{
				direction = bindingContext.HttpContext.Request.Query[groupDirection].ToString();
			}

			if (!string.IsNullOrEmpty(field) && !string.IsNullOrEmpty(direction))
			{
				sortList.Add(new TableSort(
					field,
					direction
				));
			}
		}

		bindingContext.Result = ModelBindingResult.Success(sortList);
		return Task.CompletedTask;
	}
}