#!/usr/bin/env python

import os
from subprocess import Popen, PIPE
import sys

import dbus
import dbus.mainloop.glib

import gtk

from wader.utils.utilities import save_file, get_file_data

from wader.gtk.controllers.main import MainController
from wader.gtk.models.main import MainModel
from wader.gtk.views.main import MainView
from wader.gtk.consts import GTK_LOCK, APP_LONG_NAME

def check_if_running():
    if not os.path.exists(GTK_LOCK):
        # if there's no lock we're cool
        return False

    cmd = "ps aux | grep 'wader-gtk' | grep -v grep | grep python | awk '{ print $2 }'"
    pipe = Popen(cmd, shell=True, stdout=PIPE).stdout
    pid = pipe.read().strip()
    saved_pid = get_file_data(GTK_LOCK).strip()
    if not pid and not saved_pid:
        # this shouldn't happen
        return False

    pids = pid.split('\n')
    if len(pids) > 1:
        # there's already a window running, plus us
        return True

    # for the sake of completness
    if int(pid) == int(saved_pid):
        return True
    else:
        return False

def raise_window():
    os.system("wmctrl -a '%s'" % APP_LONG_NAME)

def main():
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    model = MainModel()
    ctrl = MainController(model)
    view = MainView(ctrl)

    view.show()

    # save the pid
    try:
        os.unlink(GTK_LOCK)
    except:
        pass
    save_file(GTK_LOCK, "%s" % str(os.getpid()))

    try:
        gtk.main()
    except KeyboardInterrupt:
        print "Removing gtk lock..."
        os.unlink(GTK_LOCK)

if __name__ == '__main__':
    if check_if_running():
        raise_window()
    else:
        main()

