from unittest import TestCase
from unittest.mock import MagicMock, patch

from lib.instance.journal_chart_async_lib import (
    request_wants_journal_ajax,
    schedule_journal_exchange_chart,
)


class _FakeHeaders(dict):
    def get(self, key, default=None):
        for k, v in self.items():
            if str(k).lower() == str(key).lower():
                return v
        return default


class JournalChartAsyncLibTests(TestCase):
    def test_request_wants_journal_ajax_xhr(self):
        req = MagicMock()
        req.headers = _FakeHeaders({"X-Requested-With": "XMLHttpRequest"})
        req.form = {}
        self.assertTrue(request_wants_journal_ajax(req))

    def test_request_wants_journal_ajax_form(self):
        req = MagicMock()
        req.headers = _FakeHeaders({})
        req.form = {"ajax": "1"}
        self.assertTrue(request_wants_journal_ajax(req))

    def test_request_wants_journal_ajax_plain(self):
        req = MagicMock()
        req.headers = _FakeHeaders({"Accept": "text/html"})
        req.form = {}
        self.assertFalse(request_wants_journal_ajax(req))

    @patch("lib.instance.journal_chart_async_lib.threading.Thread")
    def test_schedule_starts_daemon_thread(self, mock_thread_cls):
        thread = MagicMock()
        mock_thread_cls.return_value = thread
        schedule_journal_exchange_chart(
            entry_id="abc123",
            exchange_symbol="BTC/USDT:USDT",
            title_prefix="t",
            journal_tfs=["5m", "15m"],
            journal_limit=100,
            marker_payload={},
            upload_folder="/tmp",
            generate_chart_fn=MagicMock(),
            get_db_fn=MagicMock(),
        )
        mock_thread_cls.assert_called_once()
        kwargs = mock_thread_cls.call_args.kwargs
        self.assertTrue(kwargs.get("daemon"))
        thread.start.assert_called_once()
