#
# Copyright (c) Daniel Sheffield 2023
#
# All rights reserved
#
# THIS SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY
from itertools import chain
from pytest import mark, fixture, raises
from urwid.raw_display import Screen
from urwid import ExitMainLoop
from urwid.widget import Widget, Text
from app.activities import ActivityManager
from app.activities.ActivityManager import show_or_exit, ActivityManager

from app.palette import high_contrast, iter_palettes, solarized

@fixture
def palettes():
    return chain(iter_palettes(solarized.theme), iter_palettes(high_contrast.theme))

@fixture
def activity_manager():
    return ActivityManager()

@fixture
def widget():
    return Widget()

@mark.parametrize('screen', [
    None,
    Screen(),
])
@mark.parametrize('key, expected', [
  ((1,), None),
  ('ctrl home', None),
  ('esc', (ExitMainLoop, ""))
])
def test_show_or_exit(key, screen, palettes, expected):
    if not isinstance(expected, tuple):
        assert expected == show_or_exit(key, screen=screen, palettes=palettes)
        return
    
    with raises(expected[0]):
        show_or_exit(key, screen=screen, palettes=palettes)

def test_add(activity_manager, widget):
    assert widget == activity_manager.add(widget, 'myActivity')
    assert 'myActivity' in activity_manager.widgets
    assert widget == activity_manager.add(widget, 'myOtherActivity')
    assert 'myOtherActivity' in activity_manager.widgets
    assert 'myActivity' in activity_manager.widgets

def test_get(activity_manager, widget):
    assert activity_manager.get('myActivity') is None
    activity_manager.add(widget, 'myActivity')
    assert widget == activity_manager.get('myActivity')
    activity_manager.add(widget, 'myOtherActivity')
    assert widget == activity_manager.get('myOtherActivity')
    assert widget == activity_manager.get('myActivity')

def test_create(activity_manager):
    widget = activity_manager.create(Text, 'widget_name', 'abc', align='right')
    assert isinstance(widget, Text)
    assert activity_manager.get('widget_name') is widget
    activity_manager.show(widget)
    assert activity_manager.app is widget

def test_show(activity_manager, widget):
    assert activity_manager.app is None
    activity_manager.add(widget, 'myActivity')
    assert activity_manager.show(widget) is None
    assert activity_manager.app is widget
    assert getattr(activity_manager.app, 'original_widget', None) is None
    assert activity_manager.show(widget) is None
    assert activity_manager.app.original_widget is widget

def test_current(activity_manager, widget):
    assert activity_manager.current() is None
    activity_manager.add(widget, 'myActivity')
    activity_manager.show(widget)
    # fix requiring call twice if not a container widget
    activity_manager.show(widget)
    assert activity_manager.current() is widget
