#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import dbus
from dbus.mainloop.glib import DBusGMainLoop
import gobject
from fcntl import ioctl
from sys import argv
from os import system

# configuration options:
INITIAL_BACKLIGHT = 80 # percents
MINIMAL_BACKLIGHT = 2  # percents

BACKLIGHT_STEPS = {
                  'idle' : 50,       # percents
                  'idle_dim' : 25,   # percents
                  'idle_prelock' : 0 # percents
                  }

# define some nice dbus helper, which I really like, cause make code easier to read :)
def getDbusObject (bus, busname , objectpath , interface):
        dbusObject = bus.get_object(busname, objectpath)
        return dbus.Interface(dbusObject, dbus_interface=interface)

def idleHandler(state, *args, **kargs):
        global backlight
        print "state: " + state
        if state=='idle':
                backlight = display.GetBrightness()
                print "reference value: " + str(backlight)
        if state=='busy':
                print "back to reference: " + str(backlight)
                display.SetBrightness(backlight)
                ioctl( framebuffer, FBIOBLANK, FB_BLANK_UNBLANK )
        elif state in BACKLIGHT_STEPS:
                back = backlight * (BACKLIGHT_STEPS[state] / 100)
                if BACKLIGHT_STEPS[state]!=0 and back < MINIMAL_BACKLIGHT:
                        back = MINIMAL_BACKLIGHT
                elif BACKLIGHT_STEPS[state]==0:
                        pass # blank framebuffer here if FSO isn't doing that
                        system("xset -display localhost:0 s blank")
                        system("xset -display localhost:0 s activate")
                        ioctl( framebuffer, FBIOBLANK, FB_BLANK_POWERDOWN )

                print "new value: " + str(back)
                display.SetBrightness(back)

DBusGMainLoop(set_as_default=True)
mainloop = gobject.MainLoop()
bus = dbus.SystemBus()

display = getDbusObject (bus, "org.freesmartphone.odeviced", "/org/freesmartphone/Device/Display/0", "org.freesmartphone.Device.Display")
bus.add_signal_receiver(idleHandler, dbus_interface="org.freesmartphone.Device.IdleNotifier", signal_name="State")

framebuffer = open( "/dev/fb0" )
FBIOBLANK = 0x4611
FB_BLANK_UNBLANK = 0
FB_BLANK_POWERDOWN = 4

backlight = INITIAL_BACKLIGHT
print "initial value: " + str(backlight)
display.SetBrightness(backlight)

try:
  mainloop.run()
except KeyboardInterrupt:
  mainloop.quit()
