require("test/setup")
require("ball")

---@return Fielding, Fielder someBaseman
local function fieldersAtDefaultPositions()
    local fielding = Fielding.new()
    fielding:resetFielderPositions()

    local fielderCount = 0
    for _, fielder in pairs(fielding.fielders) do
        fielder.x = fielder.targets[#fielder.targets].x
        fielder.y = fielder.targets[#fielder.targets].y
        fielderCount = fielderCount + 1
    end

    return fielding, fielding.fielders.second
end

---@param x number
---@param y number
---@param z number | nil
local function ballAt(x, y, z)
    local ball = Ball.new(playdate.graphics.animator)
    ball.x = x
    ball.y = y
    ball.z = z
    return ball
end

function testBallPickedUpByNearbyFielders()
    local fielding, baseman = fieldersAtDefaultPositions()
    local ball = ballAt(baseman.x, baseman.y, baseman.z)

    fielding:updateFielderPositions(ball, 0.01)
    luaunit.assertIs(baseman, ball.heldBy, "Ball should be held by the nearest fielder")
end

function testBallNotPickedUpByDistantFielders()
    local fielding = fieldersAtDefaultPositions()
    local ball = ballAt(-100, -100, -100)
    fielding:updateFielderPositions(ball, 0.01)
    luaunit.assertIsNil(ball.heldBy, "Ball should be too far for any fielders to pick up")
end

function testBallNotPickedUpWhenNotCatchable()
    local fielding, baseman = fieldersAtDefaultPositions()
    local ball = ballAt(baseman.x, baseman.y, baseman.z)
    ball:markUncatchable()

    fielding:updateFielderPositions(ball, 0.01)
    luaunit.assertIsNil(ball.heldBy, "Ball should be held by the nearest fielder")
end

os.exit(luaunit.LuaUnit.run())
