# Copyright 2026 Espressif Systems (Shanghai) Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import sys
import unittest
# Mock DeviceService to avoid starting backend threads in tests
from unittest.mock import MagicMock

from PySide2.QtCore import Qt
from PySide2.QtWidgets import QApplication, QSplitter, QTabWidget

import esp_viewer.ui.generic_window

esp_viewer.ui.generic_window.DeviceService = MagicMock()

from esp_viewer.ui.generic_window import GenericWindow


class TestUILayout(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        if not QApplication.instance():
            cls.app = QApplication(sys.argv)
        else:
            cls.app = QApplication.instance()

    def test_layout_structure(self):
        profile = {
            "meta": {"name": "Test UI"},
            "gui": {"layout": {"plot_ratio": 5, "log_ratio": 1, "config_ratio": 1}},
            "parameters": [],
            "streams": [],
            "plots": [],
        }

        window = GenericWindow(profile)

        # Verify splitters
        splitters = window.findChildren(QSplitter)
        # main_s (Horizontal), left_s (Vertical)
        self.assertTrue(any(s.orientation() == Qt.Horizontal for s in splitters))
        self.assertTrue(any(s.orientation() == Qt.Vertical for s in splitters))

    def test_monitor_tabs(self):
        profile = {
            "meta": {"name": "IMU Test"},
            "monitors": [
                {"type": "table", "title": "Gestures"},
                {"type": "text", "title": "Raw Text", "stream_id": "txt"},
            ],
            "parameters": [],
            "streams": [],
            "plots": [],
        }
        window = GenericWindow(profile)
        tabs = window.findChild(QTabWidget)

        titles = [tabs.tabText(i) for i in range(tabs.count())]
        self.assertIn("Gestures", titles)
        self.assertIn("Raw Text", titles)
        self.assertIn("System Log", titles)
        self.assertIn("Data IO", titles)


if __name__ == "__main__":
    unittest.main()
