"""Tests for src/pygui/backend/visualization/trend_chart_item.py."""
import json

import pytest

# Use the session-scoped qapp fixture from conftest.py so Qt Property/Signal
# descriptors work properly.
pytestmark = pytest.mark.usefixtures("qapp")


def test_no_data_initially():
    from pygui.backend.visualization.trend_chart_item import TrendChartItem

    item = TrendChartItem()
    assert item.hasData is False


def test_append_delta_adds_point_and_sets_has_data():
    from pygui.backend.visualization.trend_chart_item import TrendChartItem

    item = TrendChartItem()
    item.appendDelta(json.dumps([[1.5, 42.0]]))

    assert item.hasData is True
    assert item._points == [(1.5, 42.0)]


def test_append_delta_accumulates_across_calls():
    from pygui.backend.visualization.trend_chart_item import TrendChartItem

    item = TrendChartItem()
    item.appendDelta(json.dumps([[0.0, 10.0]]))
    item.appendDelta(json.dumps([[1.0, 20.0]]))

    assert item._points == [(0.0, 10.0), (1.0, 20.0)]


def test_append_delta_prunes_points_older_than_60s_window():
    from pygui.backend.visualization.trend_chart_item import TrendChartItem

    item = TrendChartItem()
    item.appendDelta(json.dumps([[0.0, 10.0]]))
    item.appendDelta(json.dumps([[70.0, 20.0]]))

    assert item._points == [(70.0, 20.0)]


def test_append_delta_ignores_malformed_json():
    from pygui.backend.visualization.trend_chart_item import TrendChartItem

    item = TrendChartItem()
    item.appendDelta("not json")

    assert item._points == []
    assert item.hasData is False


def test_append_delta_skips_repaint_when_no_points_added():
    from unittest.mock import MagicMock

    from pygui.backend.visualization.trend_chart_item import TrendChartItem

    item = TrendChartItem()
    item.appendDelta(json.dumps([[1.0, 10.0]]))
    item.update = MagicMock()

    item.appendDelta("not json")

    assert item.update.called is False


def test_clear_trend_resets_points_and_has_data():
    from pygui.backend.visualization.trend_chart_item import TrendChartItem

    item = TrendChartItem()
    item.appendDelta(json.dumps([[1.0, 10.0]]))
    assert item.hasData is True

    item.clearTrend()

    assert item._points == []
    assert item.hasData is False
