"""
    SleekXMPP: The Sleek XMPP Library
    Copyright (C) 2011 Nathanael C. Fritz, Dann Martens (TOMOTON).
    This file is part of SleekXMPP.

    See the file LICENSE for copying permission.
"""

from sleekxmpp.plugins import base
from sleekxmpp.plugins.xep_0009.stanza.RPC import RPCQuery, MethodCall, MethodResponse
from sleekxmpp.stanza.iq import Iq
from sleekxmpp.xmlstream.handler.callback import Callback
from sleekxmpp.xmlstream.matcher.xpath import MatchXPath
from sleekxmpp.xmlstream.stanzabase import register_stanza_plugin
from xml.etree import cElementTree as ET
import logging



log = logging.getLogger(__name__)



class xep_0009(base.base_plugin):

    def plugin_init(self):
        self.xep = '0009'
        self.description = 'Jabber-RPC'
        #self.stanza = sleekxmpp.plugins.xep_0009.stanza

        register_stanza_plugin(Iq, RPCQuery)
        register_stanza_plugin(RPCQuery, MethodCall)
        register_stanza_plugin(RPCQuery, MethodResponse)

        self.xmpp.registerHandler(
            Callback('RPC Call', MatchXPath('{%s}iq/{%s}query/{%s}methodCall' % (self.xmpp.default_ns, RPCQuery.namespace, RPCQuery.namespace)),
            self._handle_method_call)
        )
        self.xmpp.registerHandler(
            Callback('RPC Call', MatchXPath('{%s}iq/{%s}query/{%s}methodResponse' % (self.xmpp.default_ns, RPCQuery.namespace, RPCQuery.namespace)),
            self._handle_method_response)
        )
        self.xmpp.registerHandler(
            Callback('RPC Call', MatchXPath('{%s}iq/{%s}error' % (self.xmpp.default_ns, self.xmpp.default_ns)),
            self._handle_error)
        )
        self.xmpp.add_event_handler('jabber_rpc_method_call', self._on_jabber_rpc_method_call)
        self.xmpp.add_event_handler('jabber_rpc_method_response', self._on_jabber_rpc_method_response)
        self.xmpp.add_event_handler('jabber_rpc_method_fault', self._on_jabber_rpc_method_fault)
        self.xmpp.add_event_handler('jabber_rpc_error', self._on_jabber_rpc_error)
        self.xmpp.add_event_handler('error', self._handle_error)
        #self.activeCalls = []

    def post_init(self):
        base.base_plugin.post_init(self)
        self.xmpp.plugin['xep_0030'].add_feature('jabber:iq:rpc')
        self.xmpp.plugin['xep_0030'].add_identity('automation','rpc')

    def make_iq_method_call(self, pto, pmethod, params):
        iq = self.xmpp.makeIqSet()
        iq.attrib['to'] = pto
        iq.attrib['from'] = self.xmpp.boundjid.full
        iq.enable('rpc_query')
        iq['rpc_query']['method_call']['method_name'] = pmethod
        iq['rpc_query']['method_call']['params'] = params
        return iq;

    def make_iq_method_response(self, pid, pto, params):
        iq = self.xmpp.makeIqResult(pid)
        iq.attrib['to'] = pto
        iq.attrib['from'] = self.xmpp.boundjid.full
        iq.enable('rpc_query')
        iq['rpc_query']['method_response']['params'] = params