#!/usr/bin/python

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import osso
import gobject
import subprocess
import sys
import threading
import time

def display_cb(display_state, app):

    if (display_state == osso.device_state.OSSO_DISPLAY_OFF):
        print "Display Off"
        app.stop()
    if (display_state == osso.device_state.OSSO_DISPLAY_ON):
        print "Display On"
        app.cont()

    return False

class Application():
    def __init__(self,send_sigusr1,path):
        self.path = path
        self.process = None
        if send_sigusr1 == "1":
            print "send SIGUSR1"
            self.sendsigusr1 = True
        else:
            self.sendsigusr1 = False

    def launch(self):
        self.process = subprocess.Popen(self.path)
        thread = threading.Thread(None,self.wait)
        thread.start()

    def stop(self):
        if self.sendsigusr1 == True:
            subprocess.call(['kill', '-USR1', str(self.process.pid)],shell=False)
            time.sleep(1)

        #self.process.send_signal("SIGSTOP")
        subprocess.call(['kill', '-STOP', str(self.process.pid)],shell=False)

    def cont(self):
        #self.process.send_signal("SIGCONT")
        subprocess.call(['kill', '-CONT', str(self.process.pid)],shell=False)
        
    def is_running(self):
        if self.process.poll() == None:
            return True
        else:
            return False

    def wait(self):
        try:
            self.process.communicate()
        except OSError:
            print "oserror"
        exit()

def main():
    osso_c = osso.Context("suspendprocess", "0.0.1", False)
    device = osso.DeviceState(osso_c)

    app = Application(sys.argv[1],sys.argv[2:])
    app.launch()

    device.set_display_event_cb(display_cb, user_data=app)

    if not app.is_running(): return
    loop.run()
    print "loop stopped"
    device.set_display_event_cb(None)

def exit():
    print "exit"
    loop.quit()

gobject.threads_init()
loop = gobject.MainLoop()

if __name__ == "__main__":
    main()
