#!/usr/bin/python

import sys
import gobject
import dbus
import dbus.service
import dbus.glib
from dbus.mainloop.glib import DBusGMainLoop

class DocumentParticipant:
    def __init__(self, bus_name, obj_name):
        self.session = None
        self.bus_name = bus_name
        self.obj_name = obj_name

        bus = dbus.SessionBus()
        self.proxy = bus.get_object(bus_name, obj_name)
        self.proxy_iface = dbus.Interface(self.proxy,
            dbus_interface='org.gnome.gedit.plugin.remotecontrol')

        print "call SayHello"
        print self.proxy_iface.SayHello("text-remote-control")

        self.proxy_iface.connect_to_signal("TextInserted",
                self.text_inserted_handler)
        self.proxy_iface.connect_to_signal("RangeDeleted",
                self.range_deleted_handler)

    def session_connect(self, session):
        self.session = session

    def session_disconnect(self, session):
        self.session = None

    def text_inserted_handler(self, loc, text, len):
        print "got signal insert"
        if self.session is not None:
            self.session.insert_text(self, loc, text, len)

    def range_deleted_handler(self, start, end):
        print "got signal delete"
        if self.session is not None:
            self.session.delete_range(self, start, end)

class DocumentSession:
    def __init__(self):
        self.participants = []
        pass

    def add_participant(self, editor):
        self.participants.append(editor)

    def insert_text(self, participant, loc, text, len):
        for p in self.participants:
            if p != participant:
                p.proxy_iface.InsertText(loc, text, len)

    def delete_range(self, participant, start, end):
        for p in self.participants:
            if p != participant:
                p.proxy_iface.DeleteRange(start, end)

if __name__ == '__main__':
    args = sys.argv[1:]

    participant1 = DocumentParticipant(args[0], args[1])
    participant2 = DocumentParticipant(args[2], args[3])

    session1 = DocumentSession()
    session1.add_participant(participant1)
    session1.add_participant(participant2)

    participant1.session_connect(session1)
    participant2.session_connect(session1)

    loop = gobject.MainLoop()
    loop.run()

