# -*- coding: utf-8 -*-

import gtk
import cairo
import psutil
import gobject

import adesk.plugin as Plg
import adesk.core as Core
import adesk.ui as UI

class Plugin(Plg.Plugin):
    def __init__(self, bar, settings):
        Plg.Plugin.__init__(self, bar, settings)
        self.settings = settings
        self.can_zoom = False
        self.can_show_icon = False
        self.bar = bar
        
        self.counter = 0
        self.cpu_hist = [ 0 , 0 , 0 , 0 ]
        self.current_cpu = 0
        
        gobject.timeout_add(250, self.update_cpu_info)

    def update_cpu_info(self):
        self.counter += 1 
        cpu = psutil.cpu_percent()

        self.cpu_hist = self.cpu_hist[1:]
        self.cpu_hist.append(cpu)

        #~ for i in range(4):
            #~ self.cpu_hist[i] = self.cpu_hist[i] + 1
            #~ if self.cpu_hist[i] >= 100:
                #~ self.cpu_hist[i] = 0

        if self.counter > 4:
            self.counter = 0
            cpu = int((self.cpu_hist[0] + self.cpu_hist[1] + self.cpu_hist[2] + self.cpu_hist[3]) / 4)
            #~ print 'cpu moy. 1s :', cpu
            if not cpu == self.current_cpu:
                self.bar.update()
                self.current_cpu = cpu
            
        # keep timer alive
        return True

    def onClick(self, widget, event):
        self.system.toggle()

    def resize(self):
        self.set_size_request(int(self.cfg['icon_size']/4), self.cfg['icon_size'])

    def draw(self, cr):
        x, y , width, height =  self.get_allocation()

        red = 1 * self.current_cpu / 100
        green = 1 - ( 1 * self.current_cpu / 100 )
        blue = 0.5 * self.current_cpu / 100

        cr.set_source_rgba(0.3, 0.3, 0.3, 0.2)
        cr.rectangle(x, y, width, height)
        cr.stroke()

        cr.set_source_rgba(red, green, blue, 0.5)

        y0 = y + ( height * (100-self.current_cpu) / 100) 

        cr.rectangle(x, y0, width, int(height*self.current_cpu/100))
        cr.fill()

class System(UI.PopupWindow):
    def __init__(self, plugin, bar):
        UI.PopupWindow.__init__(self, bar, plugin)
        self.plugin = plugin

