#  Copyright 2008-2015 Nokia Solutions and Networks
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

from robot.errors import DataError
from robot.utils import py2to3, type_name

from .listeners import Listeners, ListenerProxy
from .logger import LOGGER


@py2to3
class LibraryListeners(Listeners):

    def __init__(self):
        Listeners.__init__(self, listeners=None)
        self._global_listeners = {}

    def __nonzero__(self):
        return True

    def _notify_end_test(self, listener, test):
        Listeners._notify_end_test(self, listener, test)
        if listener.scope == 'TESTCASE':
            listener.call_method(listener.close)

    def _notify_end_suite(self, listener, suite):
        Listeners._notify_end_suite(self, listener, suite)
        if listener.scope == 'TESTSUITE':
            listener.call_method(listener.close)

    def end_suite(self, suite):
        for listener in self._listeners:
            self._notify_end_suite(listener, suite)
        if not suite.parent:
            for listener in self._global_listeners.values():
                listener.call_method(listener.close)

    @property
    def _listeners(self):
        # TODO: This is ugly and somewhat slow.
        # - Should rather pass context to LibraryListeners.
        # - Could re-wrapping listeners be avoided?
        from robot.running import EXECUTION_CONTEXTS
        if not EXECUTION_CONTEXTS.current:
            return []
        listeners = []
        for library in EXECUTION_CONTEXTS.current.namespace.libraries:
            if library.has_listener:
                listeners.extend(self._wrap_listeners(library))
        for listener in listeners:
            if listener.scope == 'GLOBAL':
                self._global_listeners[listener.logger] = listener
        return listeners

    def _wrap_listeners(self, library):
        listeners = []
        for listener in library.listeners:
            try:
                listeners.append(LibraryListenerProxy(listener, library.scope))
            except DataError as err:
                LOGGER.error("Taking listener '%s' into use for library '%s' failed: %s\n"
                             "Listeners are disabled for this library."
                             % (type_name(listener), library.name, err.message))
                library.has_listener = False
                return []
        return listeners


class LibraryListenerProxy(ListenerProxy):

    def __init__(self, listener, scope):
        ListenerProxy.__init__(self, listener)
        self.scope = scope

    def _get_method_names(self, name):
        names = ListenerProxy._get_method_names(self, name)
        return names + ['_' + name for name in names]
