import numpy as np

from src.repositories.battleList.typings import Creature
from src.repositories.gameWindow import creatures
from src.repositories.gameWindow.creatures import getCreaturesBars


def _image_with_bar(width, height):
    image = np.full((30, 60), 50, dtype=np.uint8)
    x, y = 10, 5
    image[y:y + height + 1, x:x + width + 1] = 0
    image[y + 1:y + height, x + 1:x + width] = 192
    return image


def test_detects_current_client_creature_bar():
    image = np.full((30, 60), 50, dtype=np.uint8)
    image[5:8, 10] = 0
    image[5:8, 40] = 0
    image[5, 11:40] = 76
    image[6, 11:40] = 113
    image[7, 11:40] = 96

    assert getCreaturesBars(image) == [(10, 5)]


def test_keeps_legacy_creature_bar_support():
    assert getCreaturesBars(_image_with_bar(26, 3)) == [(10, 5)]


def test_uses_distance_order_when_current_name_masks_do_not_match(mocker):
    battle = np.array(
        [('Cave Rat', False), ('Cave Rat', False)], dtype=Creature,
    )
    mocker.patch.object(creatures, 'getCreaturesBars', return_value=[(100, 100), (200, 200)])
    mocker.patch.object(creatures, 'hasMatrixInsideOther', return_value=False)
    make = mocker.patch.object(
        creatures,
        'makeCreature',
        side_effect=lambda name, kind, *args, **kwargs: {
            'name': name,
            'type': kind,
            'isBeingAttacked': False,
        },
    )

    result = creatures.getCreatures(
        battle, None, (0, 0), np.zeros((704, 960), dtype=np.uint8),
        [32394, 32234, 7],
    )

    assert [item['name'] for item in result] == ['Cave Rat', 'Cave Rat']
    assert make.call_count == 2
