﻿# -*- coding: utf-8 -*-
#  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; version 2 of the License.
# 
#   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.

from Plugin import Plugin
from Plugin import Option, ConfigWindow
import gtk
import time
import threading
import gobject
import datetime
try:
	import Xlib.display
	import Xlib.X
	import Xlib.XK
	import Xlib.error
	XLibOK = True
except Exception, e:
	XLibOK = False

VERSION = '0.1'

class MainClass(Plugin):

	def __init__(self, controller, msn):
		Plugin.__init__(self, controller, msn)
		self.description = _('Auto idle plugin. Works on linux with python-xlib : http://python-xlib.sourceforge.net/')
		self.authors = {'Stéphane Péralta': 'stef312_at_gmail_dot_com'}
		self.website = 'http://stef312.online.fr/'
		self.displayName = _('Auto Idle v'+VERSION)
		self.name = 'AutoIdle'
		self.enabled = False
		self.awayTimer = None
		self._msn = msn
		self.config = controller.config
		self.config.readPluginConfig(self.name)

	def start(self):
		self.enabled = True
		self.awayTimer = AwayTimer(self._msn, int(self.config.getPluginValue( self.name, 'tempo', '60' )))
		self.awayTimer.start()

	def stop(self):
		self.enabled = False
		try:
			self.awayTimer.stop()
		except Exception, e:
			print e
	
	def check(self):
		if(XLibOK):
			return (True, 'Ok')
		else:
			return (False, 'This plugin requires python-xlib.')

	def configure( self ):
		l = [ Option( 'tempo', str, 'Idle after (in seconds):', 'Idle time', self.config.getPluginValue( self.name, 'tempo', '60' ))  ]
		response = ConfigWindow( _( 'Auto Idle configuration' ), l ).run()
		
		isOK = False
		
		if response != None:
			tempo = response['tempo'].value
			
			try:
				int(tempo)
				isOK=True
			except Exception, reason:
				isOK = False
			if(isOK):
				self.config.setPluginValue( self.name, 'tempo', tempo )
				self.stop()
				self.start()
		
		return isOK

class AwayTimer(threading.Thread):
	
	def __init__(self, msn, tempo):
		threading.Thread.__init__(self)
		self.Terminated = False
		self.screen = Xlib.display.Display().screen()
		self.last_x = -1
		self.last_y = -1
		self.last_action = 0
		self._msn = msn
		self._isIdle = False
		self._tempo = tempo
	
	def run(self):
		while not self.Terminated:
			now = datetime.datetime.now()
			x = self.screen.root.query_pointer()._data["root_x"]
			y = self.screen.root.query_pointer()._data["root_y"]
			
			if(x!=self.last_x or y!=self.last_y):
				self.last_action = now
			
			self.last_x = x
			self.last_y = y
			
			delta = now-self.last_action
			
			if(not self._isIdle and delta.seconds>=self._tempo and self._msn.status=="NLN"):
				self.prevStatus = self._msn.status
				self._msn.changeStatus('idle')
				self._isIdle = True
				
			if(self._isIdle and delta.seconds==0):
				self._msn.changeStatus(self.prevStatus)
				self._isIdle = False
			
			time.sleep(1.0)
	
	def stop(self):
		self.Terminated = True
