import logging
import tkinter as tk
from tkinter.scrolledtext import ScrolledText

from pyucc.utils import logger as ulogger


def test_setup_basic_logging_and_tk_handler(tmp_path):
    try:
        root = tk.Tk()
        root.withdraw()
    except Exception:
        import pytest
        pytest.skip("Tk not available in this environment")
    text = ScrolledText(root, height=5)
    # setup logging
    ulogger.setup_basic_logging(root)
    try:
        # add tkinter handler
        ulogger.add_tkinter_handler(text, {"colors": {logging.INFO: 'black'}})
        lg = ulogger.get_logger('pyucc.test')
        lg.info('Hello logger')
        lg.error('Error here')
        # force processing cycle
        ulogger._process_global_log_queue()
        # ensure text widget has content
        content = text.get('1.0', 'end').strip()
        assert 'Hello logger' in content or 'Error here' in content
    finally:
        ulogger.shutdown_logging_system()
        try:
            root.destroy()
        except Exception:
            pass


def test_queue_putting_handler_and_temporary_level():
    q = ulogger.QueuePuttingHandler.__init__
    # Test temporary_log_level
    lg = logging.getLogger('pyucc.temp')
    old = lg.level
    with ulogger.temporary_log_level(lg, logging.DEBUG):
        assert lg.level == logging.DEBUG
    assert lg.level == old
