#!/usr/bin/python
# -*- coding: utf-8 -*-

# CpuWatcher, plugin for Cairo-Dock.
# Copyright 2011 Yann Dulieu (Nochka85)
# Based on demo_python by Fabounet.
#
# 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/>.

from __future__ import print_function

try:
	import gobject
except:
	from gi.repository import GObject as gobject

import os
from copy import deepcopy
from CDApplet import CDApplet, _


####################
### Applet class ###
####################
class Applet(CDApplet):
	def __init__(self):
		self.__timerId = None
		self.__strDisplayValue = '0.0'
		self.__firstList = []
		self.__secondList = []
		self.__bIsFirstStat = True
		self.__bAverageMode = False
		self.__bClearLabel = False
		self.__bSubDone = False
		self.__iNbCores = 0
		self.__iTotalAverageTime = 0
		self.__fTotalAverageCpu = .0
		CDApplet.__init__(self)



	##### Applet definition #####
	
	def get_config(self, keyfile):
		self.config['refresh'] 		= keyfile.getint('Configuration', 'refresh') # in milliseconds.
		self.config['myLabel']	= keyfile.get('Icon', 'name')
		self.setTimer() # I (re)start the timer each times the config has been retrieved
		print(self.cAppletName + " : Config retrieved + Timer started")


	def end(self):
		self.removeTimer()
		print(self.cAppletName + " : Bye bye.")



	##### Private methods #####
	
	def setTimer(self):
		self.removeTimer()
		self.__timerId = gobject.timeout_add(self.config['refresh'], self.action_on_loop)

	
	def removeTimer(self):
		if self.__timerId != None:
			gobject.source_remove(self.__timerId)


	def add_sub_icons(self, cpuPct):
		if len(cpuPct) == 1:
			self.__iNbCores = 1
		else:
			self.__iNbCores = len(cpuPct) - 1
		print('Number of cores : ' + str(self.__iNbCores))
		if self.__iNbCores != 1 :
			i = 1
			lSubIcons = []
			while i < (self.__iNbCores + 1):
				lSubIcons.append('Core ' + str(i))
				lSubIcons.append(self.cShareDataDir + '/icon')
				lSubIcons.append('core' + str(i))
				i += 1
			self.sub_icons.AddSubIcons(lSubIcons)


	def action_on_loop(self) :
		if self.__bIsFirstStat:
			self.__firstList = self.getDeltaTime()
		else:
			cpuPct = []
			self.__secondList= self.getDeltaTime()
			deltaTimes = deepcopy(self.__secondList)
			
			for i in range(len(self.__firstList)):
				for j in range(len(self.__firstList[i])):
					deltaTimes[i][j] -= self.__firstList[i][j]
			
			for i in range(len(deltaTimes)):
				if sum(deltaTimes[i]) != 0:
					cpuPct.append(100 - (deltaTimes[i][len(deltaTimes[i]) - 1] * 100.00 / sum(deltaTimes[i])))
				else:
					cpuPct.append(0)
			if self.__bSubDone == False:
				self.add_sub_icons(cpuPct)
				self.__bSubDone = True
			
			if self.__iNbCores != 1 :
				i = 1
				lSubIcons = []
				while i < (self.__iNbCores + 1):
					self.sub_icons.SetQuickInfo(str('%.1f' %cpuPct[i]) + '%', 'core' + str(i))
					i += 1
			
			self.__strDisplayValue = str('%.1f' %cpuPct[0]) # Pour l'instant, on force l'affichage du CPU 0 uniquement
			
			self.__firstList = self.__secondList
			self.__bIsFirstStat = False
			
			if self.__bAverageMode:
				self.__bClearLabel = True
				self.__iTotalAverageTime += 1
				self.__fTotalAverageCpu += float(self.__strDisplayValue)
				self.icon.SetLabel(\
				'Average Result :\n' + \
				'Global Cpu :' + str('%.2f' %(self.__fTotalAverageCpu / self.__iTotalAverageTime)) + '%  (' + \
				'Total time : ' + str(self.__iTotalAverageTime * self.config['refresh']/1000) + 's)')
			else:
				if self.__bClearLabel:
					self.icon.SetLabel(self.config['myLabel'])
					self.__bClearLabel = False
		self.icon.SetQuickInfo(self.__strDisplayValue + '%')
		return True


	def getCurrentStats(self):
		statFile = open("/proc/stat", "r")
		currentStats = []
		tmp = statFile.readline()
		currentStats.append(tmp.split(" ")[2:6])
		for j in range(len(currentStats[0])):
			currentStats[0][j] = int(currentStats[0][j])
		i=1
		tmp = statFile.readline()
		while tmp[0:3] == 'cpu':
			currentStats.append(tmp.split(" ")[1:5])
			for j in range(len(currentStats[i])):
				currentStats[i][j] = int(currentStats[i][j])
			tmp = statFile.readline()
			i += 1
		statFile.close()
		if len(currentStats) == 2:
			# Il n'y a qu'un seul coeur
			simpleFile = []
			simpleFile.append(currentStats[0])
			return simpleFile
		else:
			return currentStats
	

	def getDeltaTime(self):
		lStats = self.getCurrentStats()
		if self.__bIsFirstStat:
			self.__bIsFirstStat = False
		return lStats



	##### Callbacks #####


	def on_middle_click(self):
		if self.__bAverageMode:
			print(self.cAppletName + "  >>> middle clic > Stop average mode")
			self.__bAverageMode = False
			self.__iTotalAverageTime = 0
			self.__fTotalAverageCpu = .0
			# Swap the icons
			self.icon.SetIcon(self.cShareDataDir + "/icon")
		else:
			print(self.cAppletName + "  >>> middle clic > Start average mode")
			self.__bAverageMode = True
			self.__iTotalAverageTime = 1
			self.__fTotalAverageCpu = float(self.__strDisplayValue)
			# Swap the icons
			self.icon.SetIcon(self.cShareDataDir + "/icon_Average.png")

############
### Main ###
############

if __name__ == '__main__':
	Applet().run()
