"""Generate a wrapper class from DBus introspection data"""
import argparse
from textwrap import indent
import xml.etree.ElementTree as ET

from jeepney.wrappers import Introspectable
from jeepney.io.blocking import open_dbus_connection, Proxy
from jeepney import __version__

class Method:
    def __init__(self, xml_node):
        self.name = xml_node.attrib['name']
        self.in_args = []
        self.signature = []
        for arg in xml_node.findall("arg[@direction='in']"):
            try:
                name = arg.attrib['name']
            except KeyError:
                name = 'arg{}'.format(len(self.in_args))
            self.in_args.append(name)
            self.signature.append(arg.attrib['type'])

    def _make_code_noargs(self):
        return ("def {name}(self):\n"
                "    return new_method_call(self, '{name}')\n").format(
            name=self.name)

    def make_code(self):
        if not self.in_args:
            return self._make_code_noargs()

        args = ', '.join(self.in_args)
        signature = ''.join(self.signature)
        tuple = ('({},)' if len(self.in_args) == 1 else '({})').format(args)
        return ("def {name}(self, {args}):\n"
                "    return new_method_call(self, '{name}', '{signature}',\n"
                "                           {tuple})\n").format(
            name=self.name, args=args, signature=signature, tuple=tuple
        )

INTERFACE_CLASS_TEMPLATE = """
class {cls_name}(MessageGenerator):
    interface = {interface!r}

    def __init__(self, object_path={path!r},
                 bus_name={bus_name!r}):
        super().__init__(object_path=object_path, bus_name=bus_name)
"""

class Interface:
    def __init__(self, xml_node, path, bus_name):
        self.name = xml_node.attrib['name']
        self.path = path
        self.bus_name = bus_name
        self.methods = [Method(node) for node in xml_node.findall('method')]

    def make_code(self):
        cls_name = self.name.split('.')[-1]
        chunks = [INTERFACE_CLASS_TEMPLATE.format(cls_name=cls_name,
              interface=self.name, path=self.path, bus_name=self.bus_name)]
        for method in self.methods:
            chunks.append(indent(method.make_code(), ' ' * 4))
        return '\n'.join(chunks)

MODULE_TEMPLATE = '''\
"""Auto-generated DBus bindings

Generated by jeepney version {version}

Object path: {path}
Bus name   : {bus_name}
"""

from jeepney.wrappers import MessageGenerator, new_method_call

'''

# Jeepney already includes bindings for these common interfaces
IGNORE_INTERFACES = {
    'org.freedesktop.DBus.Introspectable',
    'org.freedesktop.DBus.Properties',
    'org.freedesktop.DBus.Peer',
}

def code_from_xml(xml, path, bus_name, fh):
    if isinstance(fh, (bytes, str)):
        with open(fh, 'w') as f:
            return code_from_xml(xml, path, bus_name, f)

    root = ET.fromstring(xml)
    fh.write(MODULE_TEMPLATE.format(version=__version__, path=path,
                                    bus_name=bus_name))

    i = 0
    for interface_node in root.findall('interface'):
        if interface_node.attrib['name'] in IGNORE_INTERFACES:
            continue
        fh.write(Interface(interface_node, path, bus_name).make_code())
        i += 1

    return i

def generate(path, name, output_file, bus='SESSION'):
    conn = open_dbus_connection(bus)
    introspectable = Proxy(Introspectable(path, name), conn)
    xml, = introspectable.Introspect()
    # print(xml)

    n_interfaces = code_from_xml(xml, path, name, output_file)
    print("Written {} interface wrappers to {}".format(n_interfaces, output_file))

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('-n', '--name', required=True)
    ap.add_argument('-p', '--path', required=True)
    ap.add_argument('--bus', default='SESSION')
    ap.add_argument('-o', '--output')
    args = ap.parse_args()

    output = args.output or (args.path[1:].replace('/', '_') + '.py')

    generate(args.path, args.name, output, args.bus)


if __name__ == '__main__':
    main()
