#!/usr/bin/ruby

# This is a part of the external Ruby Battery applet for Cairo-Dock
#
# Author: Eduardo Mucelli Rezende Oliveira
# E-mail: edumucelli@gmail.com or eduardom@dcc.ufmg.br
#
# 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.

# This applet monitors the battery through acpi module. It is possbile to show a dialog message
#    containing the baterry status, charge, and temperature by left-clicking on the icon.
#    Also, through the configuration panel it is possible to set the icon's label, 
#	 show the % of carge as quick info, and activate an alert message to be shown when the charge is critically low.

require 'rubygems'
require 'rbus'
require 'parseconfig'

class String
	def to_b																			# string to boolean
	    ["true", "1", "T", "t"].include?(self.downcase)
    end
end

applet_name = File.basename(Dir.getwd)						 							# nome do applet, neste caso é demo_ruby
applet_path = "/org/cairodock/CairoDock/#{applet_name}"  	 							# path where our object is stored on the bus

bus = RBus.session_bus
applet_object = bus.get_object('org.cairodock.CairoDock', applet_path)
applet_object.interface!('org.cairodock.CairoDock.applet')

class Applet

	attr_accessor :charge, :status, :temperature, :file_name, :configuration, :warned_about_critical_charge

	DialogActiveTime = 5																# dialog windows will lasts opened (in seconds)

	def initialize applet, file_name
		self.file_name = file_name
		self.configuration = get_configuration_parameters
		self.warned_about_critical_charge = false
		@icon = applet
	end
	
	def get_configuration_parameters
		conf = ParseConfig.new(File.expand_path("~/.config/cairo-dock/current_theme/plug-ins/#{self.file_name}/#{self.file_name}.conf"))
		c = {}
		c['theme'] = conf.params['Configuration']['theme']
		c['name'] = conf.params['Icon']['name']
		c['refresh'] = conf.params['Configuration']['refresh'].to_i
		c['threshold'] = conf.params['Configuration']['threshold'].to_i
		c['critical_alert'] = conf.params['Configuration']['critical alert'].to_b
		c['show_charge'] = conf.params['Configuration']['show charge'].to_b
		c
	end

	def start
		threads =[]
		threads << Thread.new {															# flow that keeps retrieving information from acpi
			while true
				refresh_battery_information
				sleep self.configuration['refresh']										# interval to check the battery information
			end
		}
		threads << Thread.new {
			verify_action																# creates another flow to receive signals
		}
		threads.each {|t| t.join}
	end
	
	def set_graphic_configurations
		@icon.SetLabel(self.configuration['name'])										# does not need to be refreshed with charge changing
		refresh_graphic_configurations
	end

	def verify_action
		@icon.connect!(:on_click) do |param|
			action_on_click
		end
		@icon.connect!(:on_answer) do |param|
			action_on_answer param														# "param" is the answer itself
		end
		@icon.connect!(:on_reload_module) do |config_has_changed|
			action_on_reload_module config_has_changed
		end
	end

	def action_on_click
		@icon.ShowDialog("Laptop battery is #{self.status.downcase}\nfilled with #{self.charge} % of charge\nand its temperature is #{self.temperature} C", DialogActiveTime)
	end

	def action_on_reload_module config_has_changed
		p "[+] our module was reloaded, welcome back!"
		if config_has_changed
			p "[+] and our config has been changed"
			self.configuration = get_configuration_parameters							# refresh the config parameters
			p "[+] Configuration theme [#{self.configuration['theme']}] name [#{self.configuration['name']}] refresh [#{self.configuration['refresh']}] threshold [#{self.configuration['threshold']}] critical alert [#{self.configuration['critical_alert']}] show charge [#{self.configuration['show_charge']}]"
			set_graphic_configurations													# and set their modifications
		else
			p "[-] but the config is the same"
		end
	end

	def refresh_battery_information																		
		self.status, charge, self.temperature = retrieve_battery_information
		if charge != self.charge														# charge has been changed in the last check
			self.charge = charge														# refresh it
			refresh_graphic_configurations												# refresh what is rendered about the charge
			check_critical_charge														# check if the charge did reach the threshold
		end
	end

	def refresh_graphic_configurations													# the graphical part that needs to change when charge does
		@icon.AddDataRenderer("gauge", 1, self.configuration['theme'])
		@icon.RenderValues([self.charge.to_f/100])										# between 0 and 1 defines the % of the battery to be rendered
		if self.configuration['show_charge']
			@icon.SetQuickInfo("#{self.charge} %")
		else
			@icon.SetQuickInfo("")
		end
	end
	
	def check_critical_charge
		if self.charge < self.configuration['threshold']												# Charge is under the defined threshold and
			if self.configuration['critical_alert'] 													# the user want to be alerted,
				unless self.warned																		# but if it already was warned once about this
					@icon.ShowDialog("The battery charge is under #{self.charge} %", DialogActiveTime)	# battery level
					self.warned_about_critical_charge = true											# register this in order to not flood the user
				end																						# with dialog each time the battery info is
			end																							# refresh.
		else																							# If the charge is over the threshold
			if self.configuration['critical_alert']														# and the user want to be alerted
				self.warned_about_critical_charge = false												# renew the necessity of warn the user.
			end
		end
	end

	def retrieve_battery_information
		raw_info = ""
		raw_temperature = ""
		IO.popen("acpi -b") { |f|
			raw_info = f.readlines.first.split(',')			
		}
		IO.popen("acpi -t") {|f|
			raw_temperature = f.readlines.last.chomp.strip.split(',').last.strip
		}
		if raw_info.first.include?("Discharging") || raw_info.first.include?("Charging")
			raw_info.delete raw_info.last
		end
		temperature = raw_temperature.split.first
		status = raw_info.first.split(':').last.strip
		charge = raw_info.last.strip.delete("%").to_i
		return status, charge, temperature
	end
end

applet = Applet.new applet_object, applet_name
applet.start
RBus.mainloop
