from flut._flut.engine import FlutRealtimeObject
from flut.dart import Duration
from flut.flutter.animation.curves import Curve, Curves

from .scroll_position import ScrollPosition


class ScrollController(FlutRealtimeObject):

    def __init__(self, initialScrollOffset: float = 0.0):
        super().__init__("ScrollController", props={"initialScrollOffset": initialScrollOffset})
        self._position: ScrollPosition | None = None

    @property
    def offset(self) -> float:
        return self._get("offset")

    @property
    def hasClients(self) -> bool:
        return self._get("hasClients")

    @property
    def position(self) -> ScrollPosition | None:
        pos_data = self._get("position")
        if pos_data is None or "_flut_oid" not in pos_data:
            self._position = None
            return None

        current_oid = pos_data["_flut_oid"]

        if self._position is not None and self._position._flut_oid == current_oid:
            return self._position

        self._position = ScrollPosition(current_oid)
        return self._position

    def releasePosition(self):
        self._position = None

    def jumpTo(self, offset: float):
        self._call_void("jumpTo", offset=offset)

    def animateTo(self, offset: float, duration: Duration, curve: Curve = Curves.easeInOut):
        self._call_void(
            "animateTo",
            offset=offset,
            duration=duration._flut_pack(),
            curve=curve._flut_pack(),
        )
