from __future__ import annotations
from typing import Sequence, Self

import time
from aclib.builtins import MatTarget

from .basewindow import BaseWindow


__all__ = [
    '_Pos',
    '_Size',
    '_Area',
    '_Areas',
    'WinTarget',
    'WinTargetEx',
]


_Pos = _Size = tuple[int, int]
_Area = tuple[int, int, int, int]
_Areas = Sequence[_Area]


class WinTarget(MatTarget):

    @classmethod
    def fromtarget(cls, target: MatTarget, bindwin: BaseWindow):
        return cls(*target.border, target.name, target.similarity, bindwin)

    def __init__(
        self, left=0, top=0, right=0, bottom=0, name='', similarity=0.0,
        bindwin: BaseWindow = BaseWindow()
    ):
        super().__init__(left, top, right, bottom, name, similarity)
        self._boundwin = bindwin

    def click_if_exists(self, wait=0.0) -> Self:
        if self:
            self._boundwin.leftclick(self.center)
            time.sleep(wait)
        return self

    def toEx(self, closepos: _Pos) -> WinTargetEx:
        return WinTargetEx.fromtarget(self, self._boundwin, closepos)


class WinTargetEx(WinTarget):

    @classmethod
    def fromtarget(cls, target: MatTarget, bindwin: BaseWindow, closepos: _Pos):
        return cls(*target.border, target.name, target.similarity, bindwin, closepos)

    def __init__(
        self, left=0, top=0, right=0, bottom=0, name='', similarity=0.0,
        bindwin: BaseWindow = BaseWindow(), closepos: _Pos = (-1, -1),
    ):
        super().__init__(left, top, right, bottom, name, similarity, bindwin)
        self._closepos = closepos

    def close_if_exists(self, wait=0.0) -> Self:
        if self:
            self._boundwin.leftclick(self._closepos)
            time.sleep(wait)
        return self
