#!/usr/bin/env python3

import uno
import unohelper

from com.sun.star.awt import XActionListener
from com.sun.star.lang import XEventListener
from com.sun.star.sheet import XRangeSelectionListener

from .easymain import Macro, dict_to_property


__all__ = [
    'EventsButton',
    'EventsRangeSelectionListener',
]


class EventsListenerBase(unohelper.Base, XEventListener):

    def __init__(self, controller, name, window=None):
        self._controller = controller
        self._name = name
        self._window = window

    @property
    def name(self):
        return self._name

    def disposing(self, event):
        self._controller = None
        if not self._window is None:
            self._window.setMenuBar(None)


class LOEvents():

    def __init__(self, obj):
        self._obj = obj

    def __contains__(self, item):
        return self.obj.hasByName(item)

    def __getitem__(self, index):
        """Index access"""
        return self.obj.getByName(index)

    def __setitem__(self, name: str, macro: dict):
        """Set macro to event

        :param name: Event name
        :type name: str
        :param macro: Macro execute in event
        :type name: dict
        """
        pv = '[]com.sun.star.beans.PropertyValue'
        args = ()
        if macro:
            url = Macro.get_url_script(macro)
            args = dict_to_property(dict(EventType='Script', Script=url))
        uno.invoke(self.obj, 'replaceByName', (name, uno.Any(pv, args)))

    @property
    def obj(self):
        return self._obj

    @property
    def names(self):
        return self.obj.ElementNames

    def remove(self, name):
        pv = '[]com.sun.star.beans.PropertyValue'
        uno.invoke(self.obj, 'replaceByName', (name, uno.Any(pv, ())))
        return


class EventsRangeSelectionListener(EventsListenerBase, XRangeSelectionListener):

    def __init__(self, controller):
        super().__init__(controller, '')

    def done(self, event):
        range_selection = event.RangeDescriptor
        print(event)
        event_name = 'range_selection_done'
        if hasattr(self._controller, event_name):
            getattr(self._controller, event_name)(range_selection)
        return

    def aborted(self, event):
        range_selection = event.RangeDescriptor
        event_name = 'range_selection_aborted'
        if hasattr(self._controller, event_name):
            getattr(self._controller, event_name)()
        return


class EventsButton(EventsListenerBase, XActionListener):

    def __init__(self, controller, name):
        super().__init__(controller, name)

    def actionPerformed(self, event):
        event_name = f'{self.name}_action'
        if hasattr(self._controller, event_name):
            getattr(self._controller, event_name)(event)
        return
