import pathlib

import numpy as np

from src.repositories.actionBar import slotIcons
from src.repositories.actionBar.config import images as actionBarImages
from src.utils.image import loadFromRGBToGray


_itemsPath = (
    pathlib.Path(slotIcons.__file__).parent.resolve() / 'images' / 'items'
)
_spellsPath = (
    pathlib.Path(slotIcons.__file__).parent.resolve() / 'images' / 'spells'
)


def _fake_screenshot(filled, sprites_path=None):
    """Baut eine Action Bar: Pfeil-Anker bei (100, 100), Icons in Slots."""
    sprites_path = sprites_path or _itemsPath
    canvas = np.full((200, 600), 54, dtype=np.uint8)
    arrows = actionBarImages['arrows']['left']
    canvas[100:100 + arrows.shape[0], 100:100 + arrows.shape[1]] = arrows
    for slot, name in filled.items():
        sprite = loadFromRGBToGray(str(sprites_path / f'{name}.png'))
        x0 = 100 + arrows.shape[1] + (slot * 2) + ((slot - 1) * 34)
        canvas[100:100 + sprite.shape[0], x0:x0 + sprite.shape[1]] = sprite
    return canvas


def test_detects_potions_in_their_slots():
    screenshot = _fake_screenshot({1: 266, 3: 268, 5: 7643})

    detected = slotIcons.detectSlotItems(screenshot)

    assert detected == {266: 1, 268: 3, 7643: 5}


def test_detects_new_potion_generation():
    screenshot = _fake_screenshot({2: 53162, 4: 7876})

    detected = slotIcons.detectSlotItems(screenshot)

    assert detected == {53162: 2, 7876: 4}


def test_detects_spells_in_their_slots():
    screenshot = _fake_screenshot(
        {1: 'exura vita', 3: 'utura gran'}, sprites_path=_spellsPath)

    detected = slotIcons.detectSlotSpells(screenshot)

    assert detected == {'exura vita': 1, 'utura gran': 3}


def test_empty_bar_detects_nothing():
    screenshot = _fake_screenshot({})

    assert slotIcons.detectSlotItems(screenshot) == {}


def test_missing_action_bar_returns_none():
    canvas = np.full((200, 600), 54, dtype=np.uint8)

    assert slotIcons.detectSlotItems(canvas) is None


def test_empty_slot_matches_no_item():
    empty = np.full((34, 34), 54, dtype=np.uint8)

    assert slotIcons.matchSlotItem(empty) is None


def test_slot_center_points_into_slot():
    screenshot = _fake_screenshot({})
    arrowsWidth = actionBarImages['arrows']['left'].shape[1]

    assert slotIcons.getSlotCenter(screenshot, 1) == (
        100 + arrowsWidth + 2 + 17, 100 + 17)
    assert slotIcons.getSlotCenter(screenshot, 2) == (
        100 + arrowsWidth + 4 + 34 + 17, 100 + 17)
