import tkinter as tk
from pyucc.gui.topbar import TopBar
import tkinter.ttk as ttk
import pyucc.config.profiles as profiles_cfg


def test_topbar_on_profile_selected(monkeypatch):
    try:
        root = tk.Tk()
        root.withdraw()
    except Exception:
        import pytest
        pytest.skip("Tk not available in this environment")
    tb = TopBar(root)

    # stub find_profile to return a sample profile
    def fake_find(name):
        return {"name": name, "paths": ["C:/tmp"], "languages": ["Python"]}

    monkeypatch.setattr(profiles_cfg, 'find_profile', fake_find)
    # set combobox selection value
    tb.profile_var.set('myprofile')
    tb._on_profile_selected()
    assert tb.current_profile is not None
    assert tb.path_var.get() == 'C:/tmp'
    assert tb.project_type_var.get() == 'Python'
    try:
        root.destroy()
    except Exception:
        pass


def test_countings_and_scanner_sorting():
    try:
        root = tk.Tk()
        root.withdraw()
    except Exception:
        import pytest
        pytest.skip("Tk not available in this environment")
    # create a temporary treeview and a local sort helper equivalent to the tabs'
    def sort_tree(tree, col_map, col, descending):
        idx = col_map.get(col, 0)
        children = list(tree.get_children(""))
        def _key(item):
            val = tree.item(item, 'values')[idx]
            if col == 'code' or col == 'size' or col == 'total':
                try:
                    return int(val)
                except Exception:
                    return 0
            try:
                return str(val).lower()
            except Exception:
                return ''
        children.sort(key=_key, reverse=descending)
        for index, item in enumerate(children):
            tree.move(item, '', index)

    # countings-like tree
    ct_tree = ttk.Treeview(root, columns=("name","path","code","comment","blank","total","lang"), show='headings')
    col_map_ct = {"name":0, "path":1, "code":2, "comment":3, "blank":4, "total":5, "lang":6}
    for vals in [
        ("a.py", "C:/a.py", 10, 1, 0, 11, 'Python'),
        ("b.py", "C:/b.py", 2, 0, 1, 3, 'Python'),
        ("c.py", "C:/c.py", 5, 0, 0, 5, 'Python'),
    ]:
        ct_tree.insert('', 'end', values=vals)
    sort_tree(ct_tree, col_map_ct, 'code', False)
    vals0 = ct_tree.item(ct_tree.get_children()[0], 'values')
    assert int(vals0[2]) == 2

    # scanner-like tree
    st_tree = ttk.Treeview(root, columns=("name","path","size","created","modified"), show='headings')
    col_map_st = {"name":0, "path":1, "size":2, "created":3, "modified":4}
    for vals in [
        ("f1", "C:/f1", 100, '', ''),
        ("f2", "C:/f2", 5, '', ''),
    ]:
        st_tree.insert('', 'end', values=vals)
    sort_tree(st_tree, col_map_st, 'size', False)
    first = st_tree.item(st_tree.get_children()[0], 'values')
    assert int(first[2]) == 5

    try:
        root.destroy()
    except Exception:
        pass
