using RolemasterDb.App.Features;

namespace RolemasterDb.App.Frontend.AppState;

public static class TableContextCellResolver
{
    public static CriticalTableCellDetail? FindCell(CriticalTableDetail detail, TableContextSnapshot? context)
    {
        ArgumentNullException.ThrowIfNull(detail);

        if (context is null)
        {
            return null;
        }

        if (context.ResultId is { } resultId)
        {
            var matchedByResultId = detail.Cells.FirstOrDefault(cell => cell.ResultId == resultId);
            if (matchedByResultId is not null)
            {
                return matchedByResultId;
            }
        }

        if (string.IsNullOrWhiteSpace(context.RollBand) && string.IsNullOrWhiteSpace(context.ColumnKey) && string.IsNullOrWhiteSpace(context.GroupKey))
        {
            return null;
        }

        return detail.Cells.FirstOrDefault(cell => string.Equals(cell.RollBand, context.RollBand, StringComparison.Ordinal) && string.Equals(cell.ColumnKey, context.ColumnKey, StringComparison.Ordinal) && string.Equals(cell.GroupKey ?? string.Empty, context.GroupKey ?? string.Empty, StringComparison.Ordinal));
    }
}