#!/usr/bin/env python
from gi.repository import Gtk, Gdk, GdkX11, WebKit2, Gio
import sys
import os
import argparse

parser = argparse.ArgumentParser(description="XScreenSaver chainloader")
parser.add_argument("--standalone", action="store_true", help="run as standalone window instead of embedded in screensaver", dest="standalone")
parser.add_argument("--plugin", action="store", help="plugin to load")
args = parser.parse_args()

hackCalled = False
if __name__ == "__main__":
    if args.standalone:
        plug = Gtk.Window()
    else:
        plug = Gtk.Plug()

    plug.show_all()
    plug.connect("delete-event", Gtk.main_quit)
    xid = str(plug.get_window().get_xid())
    print("WINDOW ID=" + xid)
    sys.stdout.flush()

    webkit = WebKit2.WebView()
    settings = Gio.Settings("org.cinnamon.desktop.screensaver")
    if (args.plugin):
        plugin = args.plugin
    else:
        plugin = settings.get_string("screensaver-webkit-theme")

    uri = os.path.join(os.path.dirname(os.path.realpath(__file__)), plugin, "index.html")

    if os.path.isfile(uri):
        webkit.load_uri("file://" + uri)
    else:
        uri2 = os.path.join(os.getenv("HOME"), ".local/share/cinnamon-screensaver/screensavers/webkit", plugin, "index.html")
        webkit.load_uri("file://" + uri2)

    webkit.show()
    plug.add (webkit)
    Gtk.main()
