#
# Copyright (c) Daniel Sheffield 2021 - 2023
#
# All rights reserved
#
# THIS SOFTWARE IS PROVIDED AS IS WITHOUT WARRANTY
from typing import Iterator
from urwid.display_common import BaseScreen
from urwid import ExitMainLoop

def show_or_exit(key,
    screen: BaseScreen = None, palettes: Iterator = None
):

    if isinstance(key, tuple):
        return
    
    if key == 'ctrl home':
        
        if screen is None or palettes is None:
            return
        
        p = next(palettes)
        screen.register_palette(p)
        screen.clear()

    if key in ('esc',):
        raise ExitMainLoop()

class ActivityManager():

    def __init__(self):
        self.widgets = dict()
        self.app = None
    
    def add(self, widget, name):
        self.widgets[name] = widget
        return widget
    
    def get(self, name):
        if name in self.widgets:
            return self.widgets[name]
        return None
    
    def create(self, cls, name, *args, **kwargs):
        widget = cls(*args, **kwargs)
        if name is not None:
            self.add(widget, name)
        return widget
    
    def show(self, widget):
        if self.app is not None:
            self.app.original_widget = widget
            return
        self.app = widget

    def current(self):
        if self.app is None:
            return None
        return self.app.original_widget
