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

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_default},
                 bus_name{name_default}):
        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_default='' if self.path is None else f'={self.path!r}',
            name_default='' if self.bus_name is None else f'={self.bus_name!r}'
        )]
        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_from_introspection(path, name, output_file, bus='SESSION'):
    # Many D-Bus services have a main object at a predictable name, e.g.
    # org.freedesktop.Notifications -> /org/freedesktop/Notifications
    if not path:
        path = '/' + name.replace('.', '/')

    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 generate_from_file(input_file, path, name, output_file):
    with open(input_file, encoding='utf-8') as f:
        xml = f.read()

    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(
        description="Generate a simple wrapper module to call D-Bus methods.",
        epilog="If you don't use --file, this will connect to D-Bus and introspect the "
               "given name and path. --name and --path can also be used with --file, "
               "to give defaults for the generated class."
    )
    ap.add_argument('-n', '--name',
                    help='Bus name to introspect, required unless using file')
    ap.add_argument('-p', '--path',
                    help='Object path to introspect. If not specified, a path matching '
                         'the name will be used, e.g. /org/freedesktop/Notifications for org.freedesktop.Notifications')
    ap.add_argument('--bus', default='SESSION',
                    help='Bus to connect to for introspection (SESSION/SYSTEM), default SESSION')
    ap.add_argument('-f', '--file',
                    help='XML file to use instead of D-Bus introspection')
    ap.add_argument('-o', '--output',
                    help='Output filename')
    args = ap.parse_args()

    if not (args.file or args.name):
        sys.exit("Either --name or --file is required")

    # If no --output, guess a (hopefully) reasonable name.
    if args.output:
        output = args.output
    elif args.file:
        output = os.path.splitext(os.path.basename(args.file))[0] + '.py'
    elif args.path and len(args.path) > 1:
        output = args.path[1:].replace('/', '_') + '.py'
    else:  # e.g. path is '/'
        output = args.name.replace('.', '_') + '.py'

    if args.file:
        generate_from_file(args.file, args.path, args.name, output)
    else:
        generate_from_introspection(args.path, args.name, output, args.bus)


if __name__ == '__main__':
    main()
