from src.gameplay.core.tasks.bbot import BBotSayTask
from src.gameplay.core.tasks.bbotMacro import (
    BBotDelayTask, BBotMacroTask, MoveKeyTask, PauseTask,
    PickupFromGroundTask, UseBackpackItemOnTask, WaitTask,
)
from src.gameplay.core.tasks.rightClickUse import RightClickUseTask
from src.gameplay.core.tasks.setNextWaypoint import SetNextWaypointTask


def _waypoint(steps):
    return {
        'coordinate': (100, 200, 7), 'label': '', 'ignore': False,
        'options': {'action': 'macro', 'steps': steps},
    }


def test_macro_task_builds_children_in_order():
    waypoint = _waypoint([
        {'action': 'useMap', 'coordinate': (101, 200, 7)},
        {'action': 'useItemOn', 'itemId': 3304, 'coordinate': None},
        {'action': 'pickup', 'itemId': 8826, 'coordinate': (99, 200, 7)},
        {'action': 'say', 'text': 'hi'},
        {'action': 'wait', 'ms': 2000},
        {'action': 'move', 'direction': 'E'},
        {'action': 'pause'},
    ])

    task = BBotMacroTask(waypoint)
    task.onBeforeStart({})

    types = [type(child) for child in task.tasks]
    assert types == [
        RightClickUseTask, UseBackpackItemOnTask, PickupFromGroundTask,
        BBotSayTask, WaitTask, MoveKeyTask, PauseTask, SetNextWaypointTask,
    ]
    assert task.tasks[1].coordinate == waypoint['coordinate']
    assert task.tasks[4].delayAfterComplete == 2.0
    for child in task.tasks[:-1]:
        assert child.rootTask is task


def test_delay_task_waits_and_advances():
    waypoint = {
        'coordinate': (100, 200, 7), 'label': '', 'ignore': False,
        'options': {'seconds': 5},
    }

    task = BBotDelayTask(waypoint)
    task.onBeforeStart({})

    assert isinstance(task.tasks[0], WaitTask)
    assert task.tasks[0].delayAfterComplete == 5
    assert isinstance(task.tasks[1], SetNextWaypointTask)


def test_unequip_helmet_is_logged_not_executed(mocker):
    logSpy = mocker.patch(
        'src.gameplay.core.tasks.bbotMacro.logEvent')
    waypoint = _waypoint([{'action': 'unequipHelmet'}])

    task = BBotMacroTask(waypoint)
    task.onBeforeStart({})

    assert len(task.tasks) == 1  # nur SetNextWaypointTask
    logSpy.assert_called_once_with(
        'macroStepUnsupported', {'step': 'unequipHelmet'})


from src.gameplay.core.tasks.bbotMacro import (
    CloseClientTask, LogoutTask_, TurnKeyTask,
)


def test_turn_logout_close_steps_build():
    waypoint = _waypoint([
        {'action': 'turn', 'direction': 'W'},
        {'action': 'logout'},
        {'action': 'closeClient'},
    ])

    task = BBotMacroTask(waypoint)
    task.onBeforeStart({})

    types = [type(child) for child in task.tasks]
    assert types == [TurnKeyTask, LogoutTask_, CloseClientTask, SetNextWaypointTask]
