# -*- Mode: python -*-

import dbus
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk


def add_note(msg):

    def get_reminder(desc):
        get_reminder.reminder = None

        # callback functions for the GUI
        def no_reminder(button, ww):
            get_reminder.reminder = ""
            ww.destroy()

        def date_time_cb(button, ww, cal, cb, hours, minutes):
            ymd = list(cal.get_date())
            ymd[1] += 1
            get_reminder.reminder = "/".join([str(v) for v in ymd])
            if cb.get_active():
                get_reminder.reminder += "".join([" at ", "%02d" % hours.get_value_as_int(), ":", "%02d" % minutes.get_value_as_int()])
            ww.destroy()

        def day_selected(cal, exp):
            ymd = list(cal.get_date())
            ymd[1] += 1
            exp.set_label("/".join(str(vv) for vv in ymd))

        def custom(button, ww, entry):
            get_reminder.reminder = entry.get_text()
            ww.destroy()


        # Check if the user wants a reminder in a dialog box
        win = Gtk.Window()
        win.set_title("Reminder")
        win.connect("destroy", Gtk.main_quit)
        win.set_position(Gtk.WindowPosition.CENTER)
        table = Gtk.Table(n_rows=2, n_columns=7)
        win.add(table)
        table.attach(Gtk.Label(label=desc), 0, 2, 0, 1)
        # no reminder
        button = Gtk.Button(label="No reminder")
        button.connect("clicked", no_reminder, win)
        table.attach(button, 0, 1, 1, 2,
            xoptions=Gtk.AttachOptions.FILL, yoptions=0, ypadding=4)
        table.attach(Gtk.HSeparator(), 0, 2, 2, 3)
        # date / time reminder
        button = Gtk.Button(label="Date/Time")
        table.attach(button, 0, 1, 3, 4,
            xoptions=Gtk.AttachOptions.FILL,
            yoptions=Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL, ypadding=4)
        hbox = Gtk.HBox()
        table.attach(hbox, 1, 2, 3, 4)
        cal = Gtk.Calendar()
        exp = Gtk.Expander()
        day_selected(cal, exp)
        cal.connect("day-selected", day_selected, exp)
        exp.add(cal)
        hbox.pack_start(exp, False, False, 5)
        cb = Gtk.CheckButton(label="at")
        hbox.pack_start(cb, False, False, 5)
        hours = Gtk.SpinButton.new(Gtk.Adjustment(
            value=12.0, lower=0.0, upper=24.0, step_increment=1.0,
            page_increment=5.0, page_size=0.0), 1.0, 0)
        hours.set_numeric(True)
        hours.set_wrap(True)
        hbox.pack_start(hours, False, False, 5)
        hbox.pack_start(Gtk.Label(label=":"), False, False, 5)
        minutes = Gtk.SpinButton.new(Gtk.Adjustment(
            value=0.0, lower=0.0, upper=59.0, step_increment=1.0,
            page_increment=5.0, page_size=0.0), 1.0, 0)
        minutes.set_numeric(True)
        minutes.set_wrap(True)
        hbox.pack_start(minutes, False, False, 5)
        button.connect("clicked", date_time_cb, win, cal, cb, hours, minutes)
        # custom
        button = Gtk.Button(label="custom")
        table.attach(button, 0, 1, 4, 5,
            xoptions=Gtk.AttachOptions.FILL, yoptions=0, ypadding=4)
        entry = Gtk.Entry()
        button.connect("clicked", custom, win, entry)
        table.attach(entry, 1, 2, 4, 5)

        # "Show note" toggle option
        table.attach(Gtk.HSeparator(), 0, 2, 5, 6)
        cb = Gtk.CheckButton(label="Show note")
        table.attach(cb, 0, 2, 6, 7)

        win.show_all()
        win.present()
        Gtk.main()
        return (get_reminder.reminder, cb.get_active())

    title = msg.Subject
    # set up contents: opening tag
    content = ["<note-content>"]
    # title
    content.append(title)
    content.append("\n\n")
    # reminder if wanted
    (reminder, show_note) = get_reminder("\n".join([msg.From, msg.Subject]))
    if reminder == None:
        return
    if reminder:
        content.extend(["!", reminder, "\n"])
    # link back to email
    msgid = msg.MessageID
    if msgid:
        if msgid[0] != "<":
            msgid = "<" + msgid
        if msgid[-1] != ">":
            msgid += ">"
        msgid = msgid.replace("<", "&lt;").replace(">", "&gt;")
        link = '<link:cm-mail uri="%s/%s">%s</link:cm-mail>' % (clawsmail.get_folderview_selected_folder().get_identifier(), msgid, msg.Subject)
        content.append(link)
    #closing tag
    content.append("</note-content>")

    # create a tomboy note
    bus = dbus.SessionBus()
    rc = bus.get_object('org.gnome.Tomboy', '/org/gnome/Tomboy/RemoteControl')
    rc_iface = dbus.Interface(rc, dbus_interface='org.gnome.Tomboy.RemoteControl')
    uri = rc_iface.CreateNamedNote(title)
    rc_iface.SetNoteContentsXml(uri, "".join(content))
    rc_iface.DisplayNote(uri)
    if not show_note:
        rc_iface.HideNote(uri)


# iterate over all notes
for msg in clawsmail.get_summaryview_selected_message_list():
    add_note(msg)

