#!/usr/bin/env python3

# SàT communication bridge
# Copyright (C) 2009-2021 Jérôme Poisson (goffi@goffi.org)

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import asyncio
from logging import getLogger
from functools import partial
from pathlib import Path
from twisted.spread import pb
from twisted.internet import reactor, defer
from twisted.internet.error import ConnectionRefusedError, ConnectError
from libervia.backend.core import exceptions
from libervia.backend.tools import config
from libervia.frontends.bridge.bridge_frontend import BridgeException

log = getLogger(__name__)


class SignalsHandler(pb.Referenceable):
    def __getattr__(self, name):
        if name.startswith("remote_"):
            log.debug("calling an unregistered signal: {name}".format(name=name[7:]))
            return lambda *args, **kwargs: None

        else:
            raise AttributeError(name)

    def register_signal(self, name, handler, iface="core"):
        log.debug("registering signal {name}".format(name=name))
        method_name = "remote_" + name
        try:
            self.__getattribute__(method_name)
        except AttributeError:
            pass
        else:
            raise exceptions.InternalError(
                "{name} signal handler has been registered twice".format(name=method_name)
            )
        setattr(self, method_name, handler)


class bridge(object):

    def __init__(self):
        self.signals_handler = SignalsHandler()

    def __getattr__(self, name):
        return partial(self.call, name)

    def _generic_errback(self, err):
        log.error(f"bridge error: {err}")

    def _errback(self, failure_, ori_errback):
        """Convert Failure to BridgeException"""
        ori_errback(
            BridgeException(
                name=failure_.type.decode("utf-8"), message=str(failure_.value)
            )
        )

    def remote_callback(self, result, callback):
        """call callback with argument or None

        if result is not None not argument is used,
        else result is used as argument
        @param result: remote call result
        @param callback(callable): method to call on result
        """
        if result is None:
            callback()
        else:
            callback(result)

    def call(self, name, *args, **kwargs):
        """call a remote method

        @param name(str): name of the bridge method
        @param args(list): arguments
            may contain callback and errback as last 2 items
        @param kwargs(dict): keyword arguments
            may contain callback and errback
        """
        callback = errback = None
        if kwargs:
            try:
                callback = kwargs.pop("callback")
            except KeyError:
                pass
            try:
                errback = kwargs.pop("errback")
            except KeyError:
                pass
        elif len(args) >= 2 and callable(args[-1]) and callable(args[-2]):
            errback = args.pop()
            callback = args.pop()
        d = self.root.callRemote(name, *args, **kwargs)
        if callback is not None:
            d.addCallback(self.remote_callback, callback)
        if errback is not None:
            d.addErrback(errback)

    def _init_bridge_eb(self, failure_):
        log.error("Can't init bridge: {msg}".format(msg=failure_))
        return failure_

    def _set_root(self, root):
        """set remote root object

        bridge will then be initialised
        """
        self.root = root
        d = root.callRemote("initBridge", self.signals_handler)
        d.addErrback(self._init_bridge_eb)
        return d

    def get_root_object_eb(self, failure_):
        """Call errback with appropriate bridge error"""
        if failure_.check(ConnectionRefusedError, ConnectError):
            raise exceptions.BridgeExceptionNoService
        else:
            raise failure_

    def bridge_connect(self, callback, errback):
        factory = pb.PBClientFactory()
        conf = config.parse_main_conf()
        get_conf = partial(config.get_conf, conf, "bridge_pb", "")
        conn_type = get_conf("connection_type", "unix_socket")
        if conn_type == "unix_socket":
            local_dir = Path(config.config_get(conf, "", "local_dir")).resolve()
            socket_path = local_dir / "bridge_pb"
            reactor.connectUNIX(str(socket_path), factory)
        elif conn_type == "socket":
            host = get_conf("host", "localhost")
            port = int(get_conf("port", 8789))
            reactor.connectTCP(host, port, factory)
        else:
            raise ValueError(f"Unknown pb connection type: {conn_type!r}")
        d = factory.getRootObject()
        d.addCallback(self._set_root)
        if callback is not None:
            d.addCallback(lambda __: callback())
        d.addErrback(self.get_root_object_eb)
        if errback is not None:
            d.addErrback(lambda failure_: errback(failure_.value))
        return d

    def register_signal(self, functionName, handler, iface="core"):
        self.signals_handler.register_signal(functionName, handler, iface)

    def action_launch(
        self, callback_id, data, profile_key="@DEFAULT@", callback=None, errback=None
    ):
        d = self.root.callRemote("action_launch", callback_id, data, profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def actions_get(self, profile_key="@DEFAULT@", callback=None, errback=None):
        d = self.root.callRemote("actions_get", profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def config_get(self, section, name, callback=None, errback=None):
        d = self.root.callRemote("config_get", section, name)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def connect(
        self,
        profile_key="@DEFAULT@",
        password="",
        options={},
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote("connect", profile_key, password, options)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def contact_add(
        self, entity_jid, profile_key="@DEFAULT@", callback=None, errback=None
    ):
        d = self.root.callRemote("contact_add", entity_jid, profile_key)
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def contact_del(
        self, entity_jid, profile_key="@DEFAULT@", callback=None, errback=None
    ):
        d = self.root.callRemote("contact_del", entity_jid, profile_key)
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def contact_get(self, arg_0, profile_key="@DEFAULT@", callback=None, errback=None):
        d = self.root.callRemote("contact_get", arg_0, profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def contact_update(
        self,
        entity_jid,
        name,
        groups,
        profile_key="@DEFAULT@",
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote("contact_update", entity_jid, name, groups, profile_key)
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def contacts_get(self, profile_key="@DEFAULT@", callback=None, errback=None):
        d = self.root.callRemote("contacts_get", profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def contacts_get_from_group(
        self, group, profile_key="@DEFAULT@", callback=None, errback=None
    ):
        d = self.root.callRemote("contacts_get_from_group", group, profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def devices_infos_get(self, bare_jid, profile_key, callback=None, errback=None):
        d = self.root.callRemote("devices_infos_get", bare_jid, profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def disco_find_by_features(
        self,
        namespaces,
        identities,
        bare_jid=False,
        service=True,
        roster=True,
        own_jid=True,
        local_device=False,
        profile_key="@DEFAULT@",
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote(
            "disco_find_by_features",
            namespaces,
            identities,
            bare_jid,
            service,
            roster,
            own_jid,
            local_device,
            profile_key,
        )
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def disco_infos(
        self,
        entity_jid,
        node="",
        use_cache=True,
        profile_key="@DEFAULT@",
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote("disco_infos", entity_jid, node, use_cache, profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def disco_items(
        self,
        entity_jid,
        node="",
        use_cache=True,
        profile_key="@DEFAULT@",
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote("disco_items", entity_jid, node, use_cache, profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def disconnect(self, profile_key="@DEFAULT@", callback=None, errback=None):
        d = self.root.callRemote("disconnect", profile_key)
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def encryption_namespace_get(self, arg_0, callback=None, errback=None):
        d = self.root.callRemote("encryption_namespace_get", arg_0)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def encryption_plugins_get(self, callback=None, errback=None):
        d = self.root.callRemote("encryption_plugins_get")
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def encryption_trust_ui_get(
        self, to_jid, namespace, profile_key, callback=None, errback=None
    ):
        d = self.root.callRemote(
            "encryption_trust_ui_get", to_jid, namespace, profile_key
        )
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def entities_data_get(self, jids, keys, profile, callback=None, errback=None):
        d = self.root.callRemote("entities_data_get", jids, keys, profile)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def entity_data_get(self, jid, keys, profile, callback=None, errback=None):
        d = self.root.callRemote("entity_data_get", jid, keys, profile)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def features_get(self, profile_key, callback=None, errback=None):
        d = self.root.callRemote("features_get", profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def history_get(
        self,
        from_jid,
        to_jid,
        limit,
        between=True,
        filters="",
        profile="@NONE@",
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote(
            "history_get", from_jid, to_jid, limit, between, filters, profile
        )
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def image_check(self, arg_0, callback=None, errback=None):
        d = self.root.callRemote("image_check", arg_0)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def image_convert(self, source, dest, arg_2, extra, callback=None, errback=None):
        d = self.root.callRemote("image_convert", source, dest, arg_2, extra)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def image_generate_preview(
        self, image_path, profile_key, callback=None, errback=None
    ):
        d = self.root.callRemote("image_generate_preview", image_path, profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def image_resize(self, image_path, width, height, callback=None, errback=None):
        d = self.root.callRemote("image_resize", image_path, width, height)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def init_pre_script(self, callback=None, errback=None):
        d = self.root.callRemote("init_pre_script")
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def is_connected(self, profile_key="@DEFAULT@", callback=None, errback=None):
        d = self.root.callRemote("is_connected", profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def main_resource_get(
        self, contact_jid, profile_key="@DEFAULT@", callback=None, errback=None
    ):
        d = self.root.callRemote("main_resource_get", contact_jid, profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def menu_help_get(self, menu_id, language, callback=None, errback=None):
        d = self.root.callRemote("menu_help_get", menu_id, language)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def menu_launch(
        self,
        menu_type,
        path,
        data,
        security_limit,
        profile_key,
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote(
            "menu_launch", menu_type, path, data, security_limit, profile_key
        )
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def menus_get(self, language, security_limit, callback=None, errback=None):
        d = self.root.callRemote("menus_get", language, security_limit)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def message_encryption_get(self, to_jid, profile_key, callback=None, errback=None):
        d = self.root.callRemote("message_encryption_get", to_jid, profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def message_encryption_start(
        self,
        to_jid,
        namespace="",
        replace=False,
        profile_key="@NONE@",
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote(
            "message_encryption_start", to_jid, namespace, replace, profile_key
        )
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def message_encryption_stop(self, to_jid, profile_key, callback=None, errback=None):
        d = self.root.callRemote("message_encryption_stop", to_jid, profile_key)
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def message_send(
        self,
        to_jid,
        message,
        subject={},
        mess_type="auto",
        extra={},
        profile_key="@NONE@",
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote(
            "message_send", to_jid, message, subject, mess_type, extra, profile_key
        )
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def namespaces_get(self, callback=None, errback=None):
        d = self.root.callRemote("namespaces_get")
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def notification_add(
        self,
        type_,
        body_plain,
        body_rich,
        title,
        is_global,
        requires_action,
        arg_6,
        priority,
        expire_at,
        extra,
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote(
            "notification_add",
            type_,
            body_plain,
            body_rich,
            title,
            is_global,
            requires_action,
            arg_6,
            priority,
            expire_at,
            extra,
        )
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def notification_delete(
        self, id_, is_global, profile_key, callback=None, errback=None
    ):
        d = self.root.callRemote("notification_delete", id_, is_global, profile_key)
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def notifications_expired_clean(
        self, limit_timestamp, profile_key, callback=None, errback=None
    ):
        d = self.root.callRemote(
            "notifications_expired_clean", limit_timestamp, profile_key
        )
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def notifications_get(self, filters, profile_key, callback=None, errback=None):
        d = self.root.callRemote("notifications_get", filters, profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def param_get_a(
        self,
        name,
        category,
        attribute="value",
        profile_key="@DEFAULT@",
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote("param_get_a", name, category, attribute, profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def param_get_a_async(
        self,
        name,
        category,
        attribute="value",
        security_limit=-1,
        profile_key="@DEFAULT@",
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote(
            "param_get_a_async", name, category, attribute, security_limit, profile_key
        )
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def param_set(
        self,
        name,
        value,
        category,
        security_limit=-1,
        profile_key="@DEFAULT@",
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote(
            "param_set", name, value, category, security_limit, profile_key
        )
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def param_ui_get(
        self,
        security_limit=-1,
        app="",
        extra="",
        profile_key="@DEFAULT@",
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote("param_ui_get", security_limit, app, extra, profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def params_categories_get(self, callback=None, errback=None):
        d = self.root.callRemote("params_categories_get")
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def params_register_app(
        self, xml, security_limit=-1, app="", callback=None, errback=None
    ):
        d = self.root.callRemote("params_register_app", xml, security_limit, app)
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def params_template_load(self, filename, callback=None, errback=None):
        d = self.root.callRemote("params_template_load", filename)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def params_template_save(self, filename, callback=None, errback=None):
        d = self.root.callRemote("params_template_save", filename)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def params_values_from_category_get_async(
        self,
        category,
        security_limit=-1,
        app="",
        extra="",
        profile_key="@DEFAULT@",
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote(
            "params_values_from_category_get_async",
            category,
            security_limit,
            app,
            extra,
            profile_key,
        )
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def presence_set(
        self,
        to_jid="",
        show="",
        statuses={},
        profile_key="@DEFAULT@",
        callback=None,
        errback=None,
    ):
        d = self.root.callRemote("presence_set", to_jid, show, statuses, profile_key)
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def presence_statuses_get(self, profile_key="@DEFAULT@", callback=None, errback=None):
        d = self.root.callRemote("presence_statuses_get", profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def private_data_delete(self, namespace, key, arg_2, callback=None, errback=None):
        d = self.root.callRemote("private_data_delete", namespace, key, arg_2)
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def private_data_get(self, namespace, key, profile_key, callback=None, errback=None):
        d = self.root.callRemote("private_data_get", namespace, key, profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def private_data_set(
        self, namespace, key, data, profile_key, callback=None, errback=None
    ):
        d = self.root.callRemote("private_data_set", namespace, key, data, profile_key)
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def profile_create(
        self, profile, password="", component="", callback=None, errback=None
    ):
        d = self.root.callRemote("profile_create", profile, password, component)
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def profile_delete_async(self, profile, callback=None, errback=None):
        d = self.root.callRemote("profile_delete_async", profile)
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def profile_is_session_started(
        self, profile_key="@DEFAULT@", callback=None, errback=None
    ):
        d = self.root.callRemote("profile_is_session_started", profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def profile_name_get(self, profile_key="@DEFAULT@", callback=None, errback=None):
        d = self.root.callRemote("profile_name_get", profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def profile_set_default(self, profile, callback=None, errback=None):
        d = self.root.callRemote("profile_set_default", profile)
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def profile_start_session(
        self, password="", profile_key="@DEFAULT@", callback=None, errback=None
    ):
        d = self.root.callRemote("profile_start_session", password, profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def profiles_list_get(
        self, clients=True, components=False, callback=None, errback=None
    ):
        d = self.root.callRemote("profiles_list_get", clients, components)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def progress_get(self, id, profile, callback=None, errback=None):
        d = self.root.callRemote("progress_get", id, profile)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def progress_get_all(self, profile, callback=None, errback=None):
        d = self.root.callRemote("progress_get_all", profile)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def progress_get_all_metadata(self, profile, callback=None, errback=None):
        d = self.root.callRemote("progress_get_all_metadata", profile)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def ready_get(self, callback=None, errback=None):
        d = self.root.callRemote("ready_get")
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def roster_resync(self, profile_key="@DEFAULT@", callback=None, errback=None):
        d = self.root.callRemote("roster_resync", profile_key)
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def session_infos_get(self, profile_key, callback=None, errback=None):
        d = self.root.callRemote("session_infos_get", profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def sub_waiting_get(self, profile_key="@DEFAULT@", callback=None, errback=None):
        d = self.root.callRemote("sub_waiting_get", profile_key)
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def subscription(
        self, sub_type, entity, profile_key="@DEFAULT@", callback=None, errback=None
    ):
        d = self.root.callRemote("subscription", sub_type, entity, profile_key)
        if callback is not None:
            d.addCallback(lambda __: callback())
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)

    def version_get(self, callback=None, errback=None):
        d = self.root.callRemote("version_get")
        if callback is not None:
            d.addCallback(callback)
        if errback is None:
            d.addErrback(self._generic_errback)
        else:
            d.addErrback(self._errback, ori_errback=errback)


class AIOSignalsHandler(SignalsHandler):

    def register_signal(self, name, handler, iface="core"):
        async_handler = lambda *args, **kwargs: defer.Deferred.fromFuture(
            asyncio.ensure_future(handler(*args, **kwargs))
        )
        return super().register_signal(name, async_handler, iface)


class AIOBridge(bridge):

    def __init__(self):
        self.signals_handler = AIOSignalsHandler()

    def _errback(self, failure_):
        """Convert Failure to BridgeException"""
        raise BridgeException(
            name=failure_.type.decode("utf-8"), message=str(failure_.value)
        )

    def call(self, name, *args, **kwargs):
        d = self.root.callRemote(name, *args, *kwargs)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    async def bridge_connect(self):
        d = super().bridge_connect(callback=None, errback=None)
        return await d.asFuture(asyncio.get_event_loop())

    def action_launch(self, callback_id, data, profile_key="@DEFAULT@"):
        d = self.root.callRemote("action_launch", callback_id, data, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def actions_get(self, profile_key="@DEFAULT@"):
        d = self.root.callRemote("actions_get", profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def config_get(self, section, name):
        d = self.root.callRemote("config_get", section, name)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def connect(self, profile_key="@DEFAULT@", password="", options={}):
        d = self.root.callRemote("connect", profile_key, password, options)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def contact_add(self, entity_jid, profile_key="@DEFAULT@"):
        d = self.root.callRemote("contact_add", entity_jid, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def contact_del(self, entity_jid, profile_key="@DEFAULT@"):
        d = self.root.callRemote("contact_del", entity_jid, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def contact_get(self, arg_0, profile_key="@DEFAULT@"):
        d = self.root.callRemote("contact_get", arg_0, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def contact_update(self, entity_jid, name, groups, profile_key="@DEFAULT@"):
        d = self.root.callRemote("contact_update", entity_jid, name, groups, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def contacts_get(self, profile_key="@DEFAULT@"):
        d = self.root.callRemote("contacts_get", profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def contacts_get_from_group(self, group, profile_key="@DEFAULT@"):
        d = self.root.callRemote("contacts_get_from_group", group, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def devices_infos_get(self, bare_jid, profile_key):
        d = self.root.callRemote("devices_infos_get", bare_jid, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def disco_find_by_features(
        self,
        namespaces,
        identities,
        bare_jid=False,
        service=True,
        roster=True,
        own_jid=True,
        local_device=False,
        profile_key="@DEFAULT@",
    ):
        d = self.root.callRemote(
            "disco_find_by_features",
            namespaces,
            identities,
            bare_jid,
            service,
            roster,
            own_jid,
            local_device,
            profile_key,
        )
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def disco_infos(self, entity_jid, node="", use_cache=True, profile_key="@DEFAULT@"):
        d = self.root.callRemote("disco_infos", entity_jid, node, use_cache, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def disco_items(self, entity_jid, node="", use_cache=True, profile_key="@DEFAULT@"):
        d = self.root.callRemote("disco_items", entity_jid, node, use_cache, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def disconnect(self, profile_key="@DEFAULT@"):
        d = self.root.callRemote("disconnect", profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def encryption_namespace_get(self, arg_0):
        d = self.root.callRemote("encryption_namespace_get", arg_0)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def encryption_plugins_get(self):
        d = self.root.callRemote("encryption_plugins_get")
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def encryption_trust_ui_get(self, to_jid, namespace, profile_key):
        d = self.root.callRemote(
            "encryption_trust_ui_get", to_jid, namespace, profile_key
        )
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def entities_data_get(self, jids, keys, profile):
        d = self.root.callRemote("entities_data_get", jids, keys, profile)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def entity_data_get(self, jid, keys, profile):
        d = self.root.callRemote("entity_data_get", jid, keys, profile)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def features_get(self, profile_key):
        d = self.root.callRemote("features_get", profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def history_get(
        self, from_jid, to_jid, limit, between=True, filters="", profile="@NONE@"
    ):
        d = self.root.callRemote(
            "history_get", from_jid, to_jid, limit, between, filters, profile
        )
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def image_check(self, arg_0):
        d = self.root.callRemote("image_check", arg_0)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def image_convert(self, source, dest, arg_2, extra):
        d = self.root.callRemote("image_convert", source, dest, arg_2, extra)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def image_generate_preview(self, image_path, profile_key):
        d = self.root.callRemote("image_generate_preview", image_path, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def image_resize(self, image_path, width, height):
        d = self.root.callRemote("image_resize", image_path, width, height)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def init_pre_script(self):
        d = self.root.callRemote("init_pre_script")
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def is_connected(self, profile_key="@DEFAULT@"):
        d = self.root.callRemote("is_connected", profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def main_resource_get(self, contact_jid, profile_key="@DEFAULT@"):
        d = self.root.callRemote("main_resource_get", contact_jid, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def menu_help_get(self, menu_id, language):
        d = self.root.callRemote("menu_help_get", menu_id, language)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def menu_launch(self, menu_type, path, data, security_limit, profile_key):
        d = self.root.callRemote(
            "menu_launch", menu_type, path, data, security_limit, profile_key
        )
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def menus_get(self, language, security_limit):
        d = self.root.callRemote("menus_get", language, security_limit)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def message_encryption_get(self, to_jid, profile_key):
        d = self.root.callRemote("message_encryption_get", to_jid, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def message_encryption_start(
        self, to_jid, namespace="", replace=False, profile_key="@NONE@"
    ):
        d = self.root.callRemote(
            "message_encryption_start", to_jid, namespace, replace, profile_key
        )
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def message_encryption_stop(self, to_jid, profile_key):
        d = self.root.callRemote("message_encryption_stop", to_jid, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def message_send(
        self,
        to_jid,
        message,
        subject={},
        mess_type="auto",
        extra={},
        profile_key="@NONE@",
    ):
        d = self.root.callRemote(
            "message_send", to_jid, message, subject, mess_type, extra, profile_key
        )
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def namespaces_get(self):
        d = self.root.callRemote("namespaces_get")
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def notification_add(
        self,
        type_,
        body_plain,
        body_rich,
        title,
        is_global,
        requires_action,
        arg_6,
        priority,
        expire_at,
        extra,
    ):
        d = self.root.callRemote(
            "notification_add",
            type_,
            body_plain,
            body_rich,
            title,
            is_global,
            requires_action,
            arg_6,
            priority,
            expire_at,
            extra,
        )
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def notification_delete(self, id_, is_global, profile_key):
        d = self.root.callRemote("notification_delete", id_, is_global, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def notifications_expired_clean(self, limit_timestamp, profile_key):
        d = self.root.callRemote(
            "notifications_expired_clean", limit_timestamp, profile_key
        )
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def notifications_get(self, filters, profile_key):
        d = self.root.callRemote("notifications_get", filters, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def param_get_a(self, name, category, attribute="value", profile_key="@DEFAULT@"):
        d = self.root.callRemote("param_get_a", name, category, attribute, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def param_get_a_async(
        self,
        name,
        category,
        attribute="value",
        security_limit=-1,
        profile_key="@DEFAULT@",
    ):
        d = self.root.callRemote(
            "param_get_a_async", name, category, attribute, security_limit, profile_key
        )
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def param_set(
        self, name, value, category, security_limit=-1, profile_key="@DEFAULT@"
    ):
        d = self.root.callRemote(
            "param_set", name, value, category, security_limit, profile_key
        )
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def param_ui_get(self, security_limit=-1, app="", extra="", profile_key="@DEFAULT@"):
        d = self.root.callRemote("param_ui_get", security_limit, app, extra, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def params_categories_get(self):
        d = self.root.callRemote("params_categories_get")
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def params_register_app(self, xml, security_limit=-1, app=""):
        d = self.root.callRemote("params_register_app", xml, security_limit, app)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def params_template_load(self, filename):
        d = self.root.callRemote("params_template_load", filename)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def params_template_save(self, filename):
        d = self.root.callRemote("params_template_save", filename)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def params_values_from_category_get_async(
        self, category, security_limit=-1, app="", extra="", profile_key="@DEFAULT@"
    ):
        d = self.root.callRemote(
            "params_values_from_category_get_async",
            category,
            security_limit,
            app,
            extra,
            profile_key,
        )
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def presence_set(self, to_jid="", show="", statuses={}, profile_key="@DEFAULT@"):
        d = self.root.callRemote("presence_set", to_jid, show, statuses, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def presence_statuses_get(self, profile_key="@DEFAULT@"):
        d = self.root.callRemote("presence_statuses_get", profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def private_data_delete(self, namespace, key, arg_2):
        d = self.root.callRemote("private_data_delete", namespace, key, arg_2)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def private_data_get(self, namespace, key, profile_key):
        d = self.root.callRemote("private_data_get", namespace, key, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def private_data_set(self, namespace, key, data, profile_key):
        d = self.root.callRemote("private_data_set", namespace, key, data, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def profile_create(self, profile, password="", component=""):
        d = self.root.callRemote("profile_create", profile, password, component)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def profile_delete_async(self, profile):
        d = self.root.callRemote("profile_delete_async", profile)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def profile_is_session_started(self, profile_key="@DEFAULT@"):
        d = self.root.callRemote("profile_is_session_started", profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def profile_name_get(self, profile_key="@DEFAULT@"):
        d = self.root.callRemote("profile_name_get", profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def profile_set_default(self, profile):
        d = self.root.callRemote("profile_set_default", profile)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def profile_start_session(self, password="", profile_key="@DEFAULT@"):
        d = self.root.callRemote("profile_start_session", password, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def profiles_list_get(self, clients=True, components=False):
        d = self.root.callRemote("profiles_list_get", clients, components)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def progress_get(self, id, profile):
        d = self.root.callRemote("progress_get", id, profile)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def progress_get_all(self, profile):
        d = self.root.callRemote("progress_get_all", profile)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def progress_get_all_metadata(self, profile):
        d = self.root.callRemote("progress_get_all_metadata", profile)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def ready_get(self):
        d = self.root.callRemote("ready_get")
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def roster_resync(self, profile_key="@DEFAULT@"):
        d = self.root.callRemote("roster_resync", profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def session_infos_get(self, profile_key):
        d = self.root.callRemote("session_infos_get", profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def sub_waiting_get(self, profile_key="@DEFAULT@"):
        d = self.root.callRemote("sub_waiting_get", profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def subscription(self, sub_type, entity, profile_key="@DEFAULT@"):
        d = self.root.callRemote("subscription", sub_type, entity, profile_key)
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())

    def version_get(self):
        d = self.root.callRemote("version_get")
        d.addErrback(self._errback)
        return d.asFuture(asyncio.get_event_loop())
