import os

from src.shared.typings import XYCoordinate
from src.utils import humanize
from src.utils.ino import sendCommandArduino
from src.utils.keyboard import _focusTibia


SCREEN_OFFSET = (
    int(os.getenv('TIBIAPILOT_SCREEN_X', '0')),
    int(os.getenv('TIBIAPILOT_SCREEN_Y', '0')),
)


def _screenCoordinate(windowCoordinate: XYCoordinate):
    return (
        windowCoordinate[0] + SCREEN_OFFSET[0],
        windowCoordinate[1] + SCREEN_OFFSET[1],
    )


def moveTo(windowCoordinate: XYCoordinate):
    _focusTibia()
    x, y = _screenCoordinate(windowCoordinate)
    sendCommandArduino(f'moveTo,{x},{y}')


def drag(x1y1: XYCoordinate, x2y2: XYCoordinate):
    moveTo(x1y1)
    humanize.reaction()
    sendCommandArduino('dragStart')
    try:
        moveTo(x2y2)
    finally:
        humanize.pause(0.08)
        sendCommandArduino('dragEnd')


def leftClick(windowCoordinate: XYCoordinate = None):
    _focusTibia()
    if windowCoordinate is not None:
        moveTo(windowCoordinate)
        humanize.reaction()
    sendCommandArduino('leftClick')


def _modifiedLeftClick(code: int, windowCoordinate: XYCoordinate = None):
    _focusTibia()
    if windowCoordinate is not None:
        moveTo(windowCoordinate)
        humanize.reaction()
    sendCommandArduino(f'keyDown,{code}')
    try:
        humanize.pause(0.06)
        sendCommandArduino('leftClick')
    finally:
        sendCommandArduino(f'keyUp,{code}')


def useClick(windowCoordinate: XYCoordinate = None):
    _modifiedLeftClick(128, windowCoordinate)


def attackClick(windowCoordinate: XYCoordinate = None):
    _modifiedLeftClick(130, windowCoordinate)


def rightClick(windowCoordinate: XYCoordinate = None):
    _focusTibia()
    if windowCoordinate is not None:
        moveTo(windowCoordinate)
        humanize.reaction()
    sendCommandArduino('rightClick')


def scroll(clicks: int):
    _focusTibia()
    humanize.reaction()
    sendCommandArduino(f'scroll,{max(-127, min(127, clicks))}')
