#!/usr/bin/env python3

import os
import sys
import time
import dbus
import dbus.service
import dbus.mainloop.glib

from gi.repository import GObject

class Agent(dbus.service.Object):
    def __init__(self, conn=None, obj_path=None):
        dbus.service.Object.__init__(self, conn, obj_path)

    @dbus.service.method("org.openobex.Agent",
                         in_signature="o", out_signature="s")
    def Request(self, path):
        print("Transfer Request")
        self.transfer = dbus.Interface(bus.get_object("org.openobex.client",
                                                      path),
                                       "org.openobex.Transfer")
        properties = self.transfer.GetProperties()
        for key in list(properties.keys()):
            print("  %s = %s" % (key, properties[key]))
        self.start = True
        return ""

    @dbus.service.method("org.openobex.Agent",
                         in_signature="ot", out_signature="")
    def Progress(self, path, transferred):
        if (self.start):
            print("Transfer Started")
            properties = self.transfer.GetProperties()
            self.transfer_size = properties['Size']
            self.start_time = time.time()
            self.start = False
        else:
            speed = transferred / abs((time.time() - self.start_time) * 1000)
            progress = ("(" + str(transferred) + "/" + str(self.transfer_size)
                        + " bytes) @ " + str(int(speed)) + " kB/s")
            out = "\rTransfer progress " + progress
            sys.stdout.write(out)
            sys.stdout.flush()
        return

    @dbus.service.method("org.openobex.Agent",
                         in_signature="o", out_signature="")
    def Complete(self, path):
        print("\nTransfer finished")
        return

    @dbus.service.method("org.openobex.Agent",
                         in_signature="os", out_signature="")
    def Error(self, path, error):
        print("\nTransfer finished with an error: %s" % (error))
        return

    @dbus.service.method("org.openobex.Agent",
                         in_signature="", out_signature="")
    def Release(self):
        mainloop.quit()
        return

if __name__ == '__main__':
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    bus = dbus.SessionBus()
    client = dbus.Interface(bus.get_object("org.openobex.client", "/"),
                            "org.openobex.Client")

    if (len(sys.argv) < 3):
        print("Usage: %s <device> <file> [file*]" % (sys.argv[0]))
        sys.exit(1)

    path = "/test/agent"
    agent = Agent(bus, path)

    mainloop = GObject.MainLoop()
    files = [os.path.realpath(f) for f in sys.argv[2:]]

    client.SendFiles({"Destination": sys.argv[1]}, files, path)

    mainloop.run()
