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

import os
import gi
import signal
import json
import webbrowser
import sys
import subprocess
import re
import time
import configparser

from multiprocessing import Event, Process
from threading import Thread
from os.path import expanduser

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib, GdkPixbuf
gi.require_version('AppIndicator3', '0.1')
from gi.repository import AppIndicator3 as appindicator
gi.require_version('Notify', '0.7')
from gi.repository import Notify as notify

import gettext, locale

entorno_usu = locale.getlocale()[0]
if entorno_usu.find("en") >= 0 or entorno_usu.find("es") >= 0 or entorno_usu.find("it") >= 0 or entorno_usu.find("pt") >= 0 or entorno_usu.find("gl") >= 0:
	idiomas = [entorno_usu]
else:
	idiomas = ['en']

print('Language: ', entorno_usu)

t = gettext.translation('slimbookbattery',
                        '/usr/share/slimbookbattery/locale',
                        languages=idiomas,
                        fallback=True,)

_ = t.gettext

#Ruta del usuario actual
user = expanduser("~")

#Comprueba que los archivos de configuración TLP personalizados existan, en caso de no estarlo se crearan copiando el que se tiene por defecto
if (os.path.isfile(user + '/.config/slimbookbattery/custom/ahorrodeenergia') and  os.path.isfile(user + '/.config/slimbookbattery/custom/equilibrado') and os.path.isfile(user + '/.config/slimbookbattery/custom/maximorendimiento')):
	print(_('strenergysavingexists1'))
	#os.system('sed -i "/CPU_SCALING_GOVERNOR_ON_AC=/ cCPU_SCALING_GOVERNOR_ON_AC=performance" ~/.config/slimbookbattery/custom/ahorrodeenergia')
	#os.system('sed -i "/#WIFI_PWR_ON_AC=/ cWIFI_PWR_ON_AC=off" ~/.config/slimbookbattery/custom/ahorrodeenergia')
	#os.system('sed -i "/#SOUND_POWER_SAVE_ON_AC=/ cSOUND_POWER_SAVE_ON_AC=0" ~/.config/slimbookbattery/custom/ahorrodeenergia')
	#os.system('sed -i "/#RADEON_POWER_PROFILE_ON_AC=/ cRADEON_POWER_PROFILE_ON_AC=low" ~/.config/slimbookbattery/custom/ahorrodeenergia')
	#os.system('sed -i "/#RADEON_DPM_STATE_ON_AC=/ cRADEON_DPM_STATE_ON_AC=battery" ~/.config/slimbookbattery/custom/ahorrodeenergia')
	#os.system('sed -i "/#RADEON_DPM_PERF_LEVEL_ON_AC=/ cRADEON_DPM_PERF_LEVEL_ON_AC=auto" ~/.config/slimbookbattery/custom/ahorrodeenergia')

	print(_('strbalancedexists1'))
	#os.system('sed -i "/CPU_SCALING_GOVERNOR_ON_AC=/ cCPU_SCALING_GOVERNOR_ON_AC=performance" ~/.config/slimbookbattery/custom/equilibrado')
	#os.system('sed -i "/#WIFI_PWR_ON_AC=/ cWIFI_PWR_ON_AC=off" ~/.config/slimbookbattery/custom/equilibrado')
	#os.system('sed -i "/#SOUND_POWER_SAVE_ON_AC=/ cSOUND_POWER_SAVE_ON_AC=0" ~/.config/slimbookbattery/custom/equilibrado')
	#os.system('sed -i "/#RADEON_POWER_PROFILE_ON_AC=/ cRADEON_POWER_PROFILE_ON_AC=mid" ~/.config/slimbookbattery/custom/equilibrado')
	#os.system('sed -i "/#RADEON_DPM_STATE_ON_AC=/ cRADEON_DPM_STATE_ON_AC=performance" ~/.config/slimbookbattery/custom/equilibrado')
	#os.system('sed -i "/#RADEON_DPM_PERF_LEVEL_ON_AC=/ cRADEON_DPM_PERF_LEVEL_ON_AC=auto" ~/.config/slimbookbattery/custom/equilibrado')

	print(_('strmaximumperformanceexists1'))
	#os.system('sed -i "/CPU_SCALING_GOVERNOR_ON_AC=/ cCPU_SCALING_GOVERNOR_ON_AC=performance" ~/.config/slimbookbattery/custom/maximorendimiento')
	#os.system('sed -i "/#WIFI_PWR_ON_AC=/ cWIFI_PWR_ON_AC=off" ~/.config/slimbookbattery/custom/maximorendimiento')
	#os.system('sed -i "/#SOUND_POWER_SAVE_ON_AC=/ cSOUND_POWER_SAVE_ON_AC=0" ~/.config/slimbookbattery/custom/maximorendimiento')
	#os.system('sed -i "/#RADEON_POWER_PROFILE_ON_AC=/ cRADEON_POWER_PROFILE_ON_AC=high" ~/.config/slimbookbattery/custom/maximorendimiento')
	#os.system('sed -i "/#RADEON_DPM_STATE_ON_AC=/ cRADEON_DPM_STATE_ON_AC=performance" ~/.config/slimbookbattery/custom/maximorendimiento')
	#os.system('sed -i "/#RADEON_DPM_PERF_LEVEL_ON_AC=/ cRADEON_DPM_PERF_LEVEL_ON_AC=auto" ~/.config/slimbookbattery/custom/maximorendimiento')
else:
	os.system('mkdir ' + user + '/.config/slimbookbattery/')
	os.system('mkdir ' + user + '/.config/slimbookbattery/custom/')
	os.system('cp /usr/share/slimbookbattery/custom/ahorrodeenergia ' + user + '/.config/slimbookbattery/custom/')
	os.system('cp /usr/share/slimbookbattery/custom/equilibrado ' + user + '/.config/slimbookbattery/custom/')
	os.system('cp /usr/share/slimbookbattery/custom/maximorendimiento ' + user + '/.config/slimbookbattery/custom/')
#Comprueba que los archivos de configuración TLP por defecto existan, en caso de no estarlo se crearan copiando el que se tiene por defecto
if (os.path.isfile(user + '/.config/slimbookbattery/default/ahorrodeenergia') and  os.path.isfile(user + '/.config/slimbookbattery/default/equilibrado') and os.path.isfile(user + '/.config/slimbookbattery/default/maximorendimiento')):
	print(_('strenergysavingexists2'))
	#os.system('sed -i "/CPU_SCALING_GOVERNOR_ON_AC=/ cCPU_SCALING_GOVERNOR_ON_AC=performance" ~/.config/slimbookbattery/default/ahorrodeenergia')
	#os.system('sed -i "/#WIFI_PWR_ON_AC=/ cWIFI_PWR_ON_AC=off" ~/.config/slimbookbattery/default/ahorrodeenergia')
	#os.system('sed -i "/#SOUND_POWER_SAVE_ON_AC=/ cSOUND_POWER_SAVE_ON_AC=0" ~/.config/slimbookbattery/default/ahorrodeenergia')
	#os.system('sed -i "/#RADEON_POWER_PROFILE_ON_AC=/ cRADEON_POWER_PROFILE_ON_AC=low" ~/.config/slimbookbattery/default/ahorrodeenergia')
	#os.system('sed -i "/#RADEON_DPM_STATE_ON_AC=/ cRADEON_DPM_STATE_ON_AC=battery" ~/.config/slimbookbattery/default/ahorrodeenergia')
	#os.system('sed -i "/#RADEON_DPM_PERF_LEVEL_ON_AC=/ cRADEON_DPM_PERF_LEVEL_ON_AC=auto" ~/.config/slimbookbattery/default/ahorrodeenergia')

	print(_('strbalancedexists2'))
	#os.system('sed -i "/CPU_SCALING_GOVERNOR_ON_AC=/ cCPU_SCALING_GOVERNOR_ON_AC=performance" ~/.config/slimbookbattery/default/equilibrado')
	#os.system('sed -i "/#WIFI_PWR_ON_AC=/ cWIFI_PWR_ON_AC=off" ~/.config/slimbookbattery/default/equilibrado')
	#os.system('sed -i "/#SOUND_POWER_SAVE_ON_AC=/ cSOUND_POWER_SAVE_ON_AC=0" ~/.config/slimbookbattery/default/equilibrado')
	#os.system('sed -i "/#RADEON_POWER_PROFILE_ON_AC=/ cRADEON_POWER_PROFILE_ON_AC=mid" ~/.config/slimbookbattery/default/equilibrado')
	#os.system('sed -i "/#RADEON_DPM_STATE_ON_AC=/ cRADEON_DPM_STATE_ON_AC=performance" ~/.config/slimbookbattery/default/equilibrado')
	#os.system('sed -i "/#RADEON_DPM_PERF_LEVEL_ON_AC=/ cRADEON_DPM_PERF_LEVEL_ON_AC=auto" ~/.config/slimbookbattery/default/equilibrado')

	print(_('strmaximumperformanceexists2'))
	#os.system('sed -i "/CPU_SCALING_GOVERNOR_ON_AC=/ cCPU_SCALING_GOVERNOR_ON_AC=performance" ~/.config/slimbookbattery/default/maximorendimiento')
	#os.system('sed -i "/#WIFI_PWR_ON_AC=/ cWIFI_PWR_ON_AC=off" ~/.config/slimbookbattery/default/maximorendimiento')
	#os.system('sed -i "/#SOUND_POWER_SAVE_ON_AC=/ cSOUND_POWER_SAVE_ON_AC=0" ~/.config/slimbookbattery/default/maximorendimiento')
	#os.system('sed -i "/#RADEON_POWER_PROFILE_ON_AC=/ cRADEON_POWER_PROFILE_ON_AC=high" ~/.config/slimbookbattery/default/maximorendimiento')
	#os.system('sed -i "/#RADEON_DPM_STATE_ON_AC=/ cRADEON_DPM_STATE_ON_AC=performance" ~/.config/slimbookbattery/default/maximorendimiento')
	#os.system('sed -i "/#RADEON_DPM_PERF_LEVEL_ON_AC=/ cRADEON_DPM_PERF_LEVEL_ON_AC=auto" ~/.config/slimbookbattery/default/maximorendimiento')
else:
	os.system('mkdir ' + user + '/.config/slimbookbattery/')
	os.system('mkdir ' + user + '/.config/slimbookbattery/default/')
	os.system('cp /usr/share/slimbookbattery/default/ahorrodeenergia ' + user + '/.config/slimbookbattery/default/')
	os.system('cp /usr/share/slimbookbattery/default/equilibrado ' + user + '/.config/slimbookbattery/default/')
	os.system('cp /usr/share/slimbookbattery/default/maximorendimiento ' + user + '/.config/slimbookbattery/default/')

#Comprueba que el archivo de configuración exista, en caso de no estarlo se creara copiando el se tiene por defecto
if (os.path.isfile(user + '/.config/slimbookbattery/slimbookbattery.conf')):
	os.system('cat ' + user + '/.config/slimbookbattery/slimbookbattery.conf')
	if os.system("cat "+ user +"/.config/slimbookbattery/slimbookbattery.conf | grep 'modo_actual'") == 0:
		if os.system("cat "+ user +"/.config/slimbookbattery/slimbookbattery.conf | grep 'ahorro_animations'") == 0:
			print(_("strconfigfilecheck"))
		else:
			os.system("echo ahorro_animations = 0 >> "+ user +"/.config/slimbookbattery/slimbookbattery.conf")
			os.system("echo equilibrado_animations = 0 >> "+ user +"/.config/slimbookbattery/slimbookbattery.conf")
			os.system("echo maxrendimiento_animations = 1 >> "+ user +"/.config/slimbookbattery/slimbookbattery.conf")
	else:
		os.system('cp /usr/share/slimbookbattery/slimbookbattery.conf '+ user +'/.config/slimbookbattery/slimbookbattery.conf')
else:
	os.system('mkdir ' + user + '/.config/slimbookbattery/')
	os.system('cp /usr/share/slimbookbattery/slimbookbattery.conf ' + user + '/.config/slimbookbattery/')
	if (os.path.isfile(user + '/.config/autostart')):
		os.system('cat ' + user + '/.config/slimbookbattery/slimbookbattery.conf')
	else:
		os.system('mkdir ' + user + '/.config/autostart/')
		os.system('cp /usr/share/slimbookbattery/slimbookbattery-autostart.desktop ' + user + '/.config/autostart/')
#Se lee el archivo de configuración
config = configparser.ConfigParser()
config.read(user + '/.config/slimbookbattery/slimbookbattery.conf')
icono = int(config['CONFIGURATION']['icono'])

#Necesito reiniciar los archivos de tlp una vez
#if os.path.getmtime(user +"/.config/slimbookbattery/slimbookbattery.conf") < 1588863492.9313982:
if os.system("cat "+ user +"/.config/slimbookbattery/slimbookbattery.conf | grep 'reset_config110720'") != 0:
	print("actualizo configuraciones")
	os.system('cp /usr/share/slimbookbattery/default/ahorrodeenergia ' + user + '/.config/slimbookbattery/default/')
	os.system('cp /usr/share/slimbookbattery/default/equilibrado ' + user + '/.config/slimbookbattery/default/')
	os.system('cp /usr/share/slimbookbattery/default/maximorendimiento ' + user + '/.config/slimbookbattery/default/')
	os.system('cp /usr/share/slimbookbattery/custom/ahorrodeenergia ' + user + '/.config/slimbookbattery/custom/')
	os.system('cp /usr/share/slimbookbattery/custom/equilibrado ' + user + '/.config/slimbookbattery/custom/')
	os.system('cp /usr/share/slimbookbattery/custom/maximorendimiento ' + user + '/.config/slimbookbattery/custom/')
	os.system('cp /usr/share/slimbookbattery/slimbookbattery.conf ' + user + '/.config/slimbookbattery/slimbookbattery.conf')
	#creamos la variable reset_config en el archivo de configuración
	#configfile = open(user + '/.config/slimbookbattery/slimbookbattery.conf', 'w')
	#config.set('SETTINGS', 'reset_config', str(int(1)))
	#config.write(configfile)
	#configfile.close()

modo_actual = int(config['CONFIGURATION']['modo_actual'])

if modo_actual == 1:
	modo = "ahorrodeenergia"
elif modo_actual == 2:
	modo = "equilibrado"
elif modo_actual == 3:
	modo = "maximorendimiento"

#comprobamos brillo en caso de que sea la primera vez se usara el de por defecto.
if modo_actual == 1:
	#Ahorrodenergia
	brightness = int(config['SETTINGS']['ahorro_brightness'])
elif modo_actual == 2:
	#equilibrado
	brightness = int(config['SETTINGS']['equilibrado_brightness'])
elif modo_actual == 3:
	#maximorendimiento
	brightness = int(config['SETTINGS']['maxrendimiento_brightness'])

if os.path.isdir("/sys/class/backlight"):
		for name in os.listdir("/sys/class/backlight"):
			if os.path.isfile("/sys/class/backlight/"+ name +"/max_brightness") and os.path.isfile("/sys/class/backlight/"+ name +"/brightness"):
				brilloMax = int(subprocess.getoutput("cat /sys/class/backlight/"+ name +"/max_brightness"))
				brightness = int((brilloMax / 100) * brightness)
				print((_('strbrightness')) +str(brightness))
				os.system('/usr/share/slimbookbattery/bin/brillo.x '+ str(brightness) + ' '+ str(name))

#Comprueba si usa gráficos nvidia, si es el caso se guarda en una variable el valor de los gráficos que esta usando ahora mismo (Nvidia o Intel)
if os.system('prime-select query') == 0:
	graphicsBefore = subprocess.getoutput('prime-select query')

if (config['CONFIGURATION']['autostart'] == '0' and config['CONFIGURATION']['application_on'] == '1'):
	if os.system("pkexec python3 /usr/share/slimbookbattery/slimbookbattery-changemode.pyc " + modo + " " + user + " 'start'") == 0:
		print(_('strpasswordcorrect'))
		if os.system('echo $XDG_CURRENT_DESKTOP | grep -i gnome') == 0:
			if modo == 'ahorrodeenergia':
				if config['SETTINGS']['ahorro_animations'] == "0":
					os.system('dconf write /org/gnome/desktop/interface/enable-animations false')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-app-switch false')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-window-launch false')
				else:
					os.system('dconf write /org/gnome/desktop/interface/enable-animations true')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-app-switch true')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-window-launch true')
			elif modo == 'equilibrado':
				if config['SETTINGS']['equilibrado_animations'] == '0':
					os.system('dconf write /org/gnome/desktop/interface/enable-animations false')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-app-switch false')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-window-launch false')
				else:
					os.system('dconf write /org/gnome/desktop/interface/enable-animations true')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-app-switch true')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-window-launch true')
			elif modo == 'maximorendimiento':
				if config['SETTINGS']['maxrendimiento_animations'] == '0':
					os.system('dconf write /org/gnome/desktop/interface/enable-animations false')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-app-switch false')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-window-launch false')
				else:
					os.system('dconf write /org/gnome/desktop/interface/enable-animations true')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-app-switch true')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-window-launch true')
	else:
		print(_('strpasswordwrong'))
		configfile = open(user + '/.config/slimbookbattery/slimbookbattery.conf', 'w')
		config.set('CONFIGURATION', 'application_on', '0')
		config.write(configfile)
		configfile.close()

#Se importa el archivo preferences
#preferences = imp.load_source("preferences", "/usr/share/slimbookbattery/preferences")

ENERGY_SAVING = '/usr/share/slimbookbattery/images/battery.png'
EQUILIBRADO = '/usr/share/slimbookbattery/images/equilibrado.png'
MAX_PERFORMANCE = '/usr/share/slimbookbattery/images/battery_high.png'
DISABLED = '/usr/share/slimbookbattery/images/disabled.png'
STATUS_NORMAL = '/usr/share/slimbookbattery/images/normal.png'
STATUS_HIGH = '/usr/share/slimbookbattery/images/high.png'
STATUS_CRITICAL = '/usr/share/slimbookbattery/images/critical.png'

APPINDICATOR_ID = 'myapp-indicator'

indicator = appindicator.Indicator.new(APPINDICATOR_ID, '', appindicator.IndicatorCategory.SYSTEM_SERVICES)
indicator.set_icon_full(DISABLED, 'Icon disabled')

'''
#Muestra el porcentaje actual de la batería nada más iniciar la aplicación
if os.path.isdir("/sys/class/power_supply/BAT1"):
	var = subprocess.Popen(["cat", "/sys/class/power_supply/BAT1/capacity"], stdout=subprocess.PIPE)
else:
	var = subprocess.Popen(["cat", "/sys/class/power_supply/BAT0/capacity"], stdout=subprocess.PIPE)
(out, err) = var.communicate()
bat_percent = int(out[0:3])

indicator.set_label(" " + str(bat_percent) + "%", APPINDICATOR_ID)
'''

proceso = None
alert = None

def main():
	#Si el valor del icono obenido de la configuración es 1 nos mostrará el indicados de la aplicación para poder interactuar, en caso contrario estará oculto.
	if icono == 1:
		indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
	else:
		indicator.set_status(appindicator.IndicatorStatus.PASSIVE)

	indicator.set_menu(build_menu())
	notify.init(APPINDICATOR_ID)
	if int(config['CONFIGURATION']['application_on']) == 1 and int(config['CONFIGURATION']['alerts']) == 1:
		#Si las alertas de los ciclos estan activos y la aplicación está encendida, comenzará el proceso para ir mostrando las alertas y además actualizará el icono del modo que se esté utilizando
		print(_("strappstatus1"))
		start_process(None)

		modo_actual = int(config['CONFIGURATION']['modo_actual'])
		if modo_actual == 1:
			indicator.set_icon_full(ENERGY_SAVING, 'Icon energy saving')
		elif modo_actual == 2:
			indicator.set_icon_full(EQUILIBRADO, 'Icon balanced')
		elif modo_actual == 3:
			indicator.set_icon_full(MAX_PERFORMANCE, 'Icon max performance')
	elif int(config['CONFIGURATION']['application_on']) == 1 and int(config['CONFIGURATION']['alerts']) == 0:
		#Si las alertas de los ciclos estan desactivadas y la aplicación está encendida, solo se actualizará el icono del modo que se esté usando
		print(_("strappstatus2"))
		modo_actual = int(config['CONFIGURATION']['modo_actual'])
		if modo_actual == 1:
			indicator.set_icon_full(ENERGY_SAVING, 'Icon energy saving')
		elif modo_actual == 2:
			indicator.set_icon_full(EQUILIBRADO, 'Icon balanced')
		elif modo_actual == 3:
			indicator.set_icon_full(MAX_PERFORMANCE, 'Icon max performance')
	elif int(config['CONFIGURATION']['application_on']) == 0 and int(config['CONFIGURATION']['alerts']) == 1:
		print(_("strappstatus3"))
		start_process(None)
	else:
		print(_("strappstatus4"))

	#Ahora que la aplicación ya se habrá iniciado si el valor de los gráficos que esta usando ahora (intel o nvidia) es distinto al valor anteriormente guardado pedirá al usuario si desea reiniciar
	if os.system('prime-select query') == 0:
		graphicsAfter = subprocess.getoutput('prime-select query')
		if graphicsBefore != graphicsAfter:
			rebootNvidia()
	Gtk.main()

def build_menu():
	menu = Gtk.Menu()

	#Creación de los separadores
	item_separador1 = Gtk.SeparatorMenuItem()
	item_separador2 = Gtk.SeparatorMenuItem()
	item_separador3 = Gtk.SeparatorMenuItem()

	#Imagenes a utilizar para los iconos del menú
	pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(
			filename='/usr/share/slimbookbattery/images/normal.png',
			width=25,
			height=25,
			preserve_aspect_ratio=True)
	icon_ahorro = Gtk.Image.new_from_pixbuf(pixbuf)

	
	pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(
			filename='/usr/share/slimbookbattery/images/balanced_normal.png',
			width=25,
			height=25,
			preserve_aspect_ratio=True)
	icon_equilibrado = Gtk.Image.new_from_pixbuf(pixbuf)

	pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(
			filename='/usr/share/slimbookbattery/images/performance_normal.png',
			width=25,
			height=25,
			preserve_aspect_ratio=True)
	icon_max_rendimiento = Gtk.Image.new_from_pixbuf(pixbuf)

	pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(
			filename='/usr/share/slimbookbattery/images/disabled_normal.png',
			width=25,
			height=25,
			preserve_aspect_ratio=True)
	icon_apagado = Gtk.Image.new_from_pixbuf(pixbuf)
	icon_apagado.set_pixel_size(24)
	
	#Creación de cada ImageMenuItem
	item_modo1 = Gtk.ImageMenuItem()
	item_modo1.set_label(_('strenergysaving'))
	item_modo1.connect('activate', modo_ahorro)
	item_modo1.set_image(icon_ahorro)
	item_modo1.set_always_show_image(True)

	item_modo2 = Gtk.ImageMenuItem()
	item_modo2.set_label(_('strbalanced'))
	item_modo2.connect('activate', modo_equilibrado)
	item_modo2.set_image(icon_equilibrado)
	item_modo2.set_always_show_image(True)

	item_modo3 = Gtk.ImageMenuItem()
	item_modo3.set_label(_('strmaximumperformance'))
	item_modo3.connect('activate', modo_max_rendimiento)
	item_modo3.set_image(icon_max_rendimiento)
	item_modo3.set_always_show_image(True)

	item_apagar = Gtk.ImageMenuItem()
	item_apagar.set_label(_('stroffoption'))
	item_apagar.connect('activate', modo_apagado)
	item_apagar.set_image(icon_apagado)
	item_apagar.set_always_show_image(True)

	item_avanzado = Gtk.MenuItem()
	item_avanzado.set_label(_('stradvancedmode'))
	item_avanzado.connect('activate', modo_avanzado)

	item_salir = Gtk.MenuItem()
	item_salir.set_label(_('strexitoption'))
	item_salir.connect('activate', salir)

	#Se añaden los items al menú en orden
	menu.append(item_modo1)
	menu.append(item_modo2)
	menu.append(item_modo3)
	menu.append(item_separador1)
	menu.append(item_apagar)
	menu.append(item_separador2)
	menu.append(item_avanzado)
	menu.append(item_separador3)
	menu.append(item_salir)

	menu.show_all()

	#Cada minuto va actualizando la información del porcentaje de carga que se verá al lado del icono del indicator
	#GLib.timeout_add(60000, change_label, indicator)

	return menu

'''
def change_label(indicator):
	if os.path.isdir("/sys/class/power_supply/BAT1"):
		var = subprocess.Popen(["cat", "/sys/class/power_supply/BAT1/capacity"], stdout=subprocess.PIPE)
	else:
		var = subprocess.Popen(["cat", "/sys/class/power_supply/BAT0/capacity"], stdout=subprocess.PIPE)
	(out, err) = var.communicate()
	bat_percent = int(out[0:3])
	indicator.set_label(" " + str(bat_percent) + "%", APPINDICATOR_ID)
	return True


def add_menu(menu, text=None, icon=None, conector_event=None,
             conector_action=None):
    if text is not None:
        menu_item = Gtk.ImageMenuItem.new_with_label(text)
        if icon:
            image = Gtk.Image.new_from_file(icon)
            menu_item.set_image(image)
            menu_item.set_always_show_image(True)
    else:
        if icon is None:
            menu_item = Gtk.SeparatorMenuItem()
        else:
            menu_item = Gtk.ImageMenuItem.new_from_file(icon)
            menu_item.set_always_show_image(True)
    if conector_event is not None and conector_action is not None:
        menu_item.connect(conector_event, conector_action)
    menu_item.show()
    menu.append(menu_item)
    return menu_item
'''

def battery_status():
	status = ""
	global contCharging
	global numAlerts
	global contDischarging
	global tiempo
	contCharging = 1
	contDischarging = 1
	# Terminal Text Format
	t_bold = "\033[1m"
	t_end = "\033[0m"
	t_red = "\033[91m"
	t_green = "\033[92m"

	while True:
		if (os.path.isdir("/sys/class/power_supply/BAT0")):
			with open('/sys/class/power_supply/BAT0/status', 'r') as file_status:
				status = file_status.read().rstrip("\n")
		elif (os.path.isdir("/sys/class/power_supply/BAT1")):
			with open('/sys/class/power_supply/BAT1/status', 'r') as file_status:
				status = file_status.read().rstrip("\n")

		print(t_bold + "[" + status + "]" + t_end)
		config.read(user + '/.config/slimbookbattery/slimbookbattery.conf')
		max_battery = int(config['CONFIGURATION']['max_battery_value'])
		min_battery = int(config['CONFIGURATION']['min_battery_value'])
		max_times = int(config['CONFIGURATION']['max_battery_times'])
		time_warnings = int(config['CONFIGURATION']['time_between_warnings'])

		print(t_green + (_("strprintmaxbat")) + str(max_battery) + t_end)
		print(t_red + (_("strprintminbat")) + str(min_battery) + t_end)
		print(t_green + (_("strprintmaxtimes")) + str(max_times) + t_end)
		print(t_red + (_("strprinttimebwnwarnings")) + str(time_warnings) + t_end)
		config.read(user + '/.config/slimbookbattery/slimbookbattery.conf')
		numAlerts = max_times = int(config['CONFIGURATION']['max_battery_times'])
		tiempo = time_warnings = int(config['CONFIGURATION']['time_between_warnings'])
		print("")
		time.sleep(tiempo)
		if os.path.isdir("/sys/class/power_supply/BAT1"):
			var = subprocess.Popen(["cat", "/sys/class/power_supply/BAT1/capacity"], stdout=subprocess.PIPE)
		else:
			var = subprocess.Popen(["cat", "/sys/class/power_supply/BAT0/capacity"], stdout=subprocess.PIPE)
		(out, err) = var.communicate()
		bat_percent = int(out[0:3])
		print((_("strcurrentbat")), bat_percent)
		alertsConf = int(config['CONFIGURATION']['alerts'])
		if alertsConf == 1:
			alert = True
		elif alertsConf == 0:
			alert = False
			print(_('stralertsdisabled'))

		if bat_percent >= max_battery:
			if status != "Discharging":
				if alert == True:
					if contCharging <= numAlerts:
						os.system("notify-send 'Slimbook Battery' '"+ (_("strhighbatnotify1")) +str(bat_percent) + chr(37) + (_("strwarningnotify")) + str(int(contCharging)) + "/" + str(int(numAlerts)) + (_("strtimeuntilnextwarning")) + str(float(tiempo)) + (_("strsecondsnotify")) + ")' -i '" + STATUS_HIGH + "'")
						contCharging = contCharging + 1
			else:
				print(_("strhighbatnotify2"))
		elif bat_percent <= min_battery:
			if status == "Discharging":
				if alert == True:
					if contDischarging <= numAlerts:
						os.system("notify-send 'Slimbook Battery' '"+ (_("strcriticalbatnotify1")) + str(bat_percent) + chr(37) + (_("strwarningnotify")) + str(int(contDischarging)) + "/" + str(int(numAlerts)) + (_("strtimeuntilnextwarning")) + str(float(tiempo)) + (_("strsecondsnotify")) + ")' -i '" + STATUS_CRITICAL + "'")
						contDischarging = contDischarging + 1
				else:
					print(_("strcriticalbatnotify1"))
		else:
			alert = True

def start_process(val):
	global proceso

	proceso = Process(target=battery_status)

	proceso.start()

def stop_process():
	proceso.terminate()
	contCharging = 0
	contDischarging = 0

def salir(val):

	if modo_actual == 1:
		modo = "ahorrodeenergia"
	elif modo_actual == 2:
		modo = "equilibrado"
	elif modo_actual == 3:
		modo = "maximorendimiento"

	applicationState = str(config['CONFIGURATION']['application_on'])
	
	config.set('CONFIGURATION', 'application_on', str(0))
	configfile = open(user + '/.config/slimbookbattery/slimbookbattery.conf', 'w')
	config.write(configfile)
	configfile.close()

	if os.system('prime-select query') == 0:
		graphicsBefore = subprocess.getoutput('prime-select query')

	if applicationState == '1':
		if os.system("pkexec python3 /usr/share/slimbookbattery/slimbookbattery-changemode.pyc " + modo + " " + user + " 'stop'") == 0:
			if os.system('prime-select query') == 0:
				graphicsAfter = subprocess.getoutput('prime-select query')
				if graphicsBefore != graphicsAfter:
					rebootNvidia()
			#Se vuelven a activar las animaciones del sistema
			if os.system('echo $XDG_CURRENT_DESKTOP | grep -i gnome') == 0:
				os.system('dconf write /org/gnome/desktop/interface/enable-animations true')
				os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-app-switch true')
				os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-window-launch true')

			notify.uninit()
			try:
				proceso.terminate()
			except:
				print(_('strnotprocess'))
			Gtk.main_quit()
		else:
			config.set('CONFIGURATION', 'application_on', str(1))
			configfile = open(user + '/.config/slimbookbattery/slimbookbattery.conf', 'w')
			config.write(configfile)
			configfile.close()
			print(_('strpasswordwrong'))
	else:
		notify.uninit()
		try:
			proceso.terminate()
		except:
			print(_('strnotprocess'))
		Gtk.main_quit()

def modo_ahorro(val):
	config.read(user + '/.config/slimbookbattery/slimbookbattery.conf')
	modoAnterior = config['CONFIGURATION']['modo_actual']
	configfile = open(user + '/.config/slimbookbattery/slimbookbattery.conf', 'w')
	config.set('CONFIGURATION', 'modo_actual', '1')
	if config['CONFIGURATION']['application_on'] == '0':
		config.set('CONFIGURATION', 'application_on', '1')
		if int(config['CONFIGURATION']['alerts']) == 0:
			try:
				stop_process()
			except:
				print(_('strnotprocess'))
	config.write(configfile)
	configfile.close()
	if os.system('prime-select query') == 0:
		graphicsBefore = subprocess.getoutput('prime-select query')
	if cambiar_modo('ahorrodeenergia', user) == True:
		indicator.set_icon_full(ENERGY_SAVING, 'Icon energy saving')

		if os.system('prime-select query') == 0:
			graphicsAfter = subprocess.getoutput('prime-select query')
			if graphicsBefore != graphicsAfter:
				rebootNvidia()
	else:
		print(_('strpasswordwrong'))
		configfile = open(user + '/.config/slimbookbattery/slimbookbattery.conf', 'w')
		config.set('CONFIGURATION', 'modo_actual', modoAnterior)
		config.write(configfile)
		configfile.close()

def modo_equilibrado(val):
	config.read(user + '/.config/slimbookbattery/slimbookbattery.conf')
	modoAnterior = config['CONFIGURATION']['modo_actual']
	configfile = open(user + '/.config/slimbookbattery/slimbookbattery.conf', 'w')
	config.set('CONFIGURATION', 'modo_actual', '2')
	if config['CONFIGURATION']['application_on'] == '0':
		config.set('CONFIGURATION', 'application_on', '1')
		if int(config['CONFIGURATION']['alerts']) == 0:
			try:
				stop_process()
			except:
				print(_('strnotprocess'))
	config.write(configfile)
	configfile.close()
	if os.system('prime-select query') == 0:
		graphicsBefore = subprocess.getoutput('prime-select query')
	if cambiar_modo('equilibrado', user) == True:
		indicator.set_icon_full(EQUILIBRADO, 'Icon balanced')

		if os.system('prime-select query') == 0:
			graphicsAfter = subprocess.getoutput('prime-select query')
			if graphicsBefore != graphicsAfter:
				rebootNvidia()
	else:
		print(_('strpasswordwrong'))
		configfile = open(user + '/.config/slimbookbattery/slimbookbattery.conf', 'w')
		config.set('CONFIGURATION', 'modo_actual', modoAnterior)
		config.write(configfile)
		configfile.close()

def modo_max_rendimiento(val):
	config.read(user + '/.config/slimbookbattery/slimbookbattery.conf')
	modoAnterior = config['CONFIGURATION']['modo_actual']
	configfile = open(user + '/.config/slimbookbattery/slimbookbattery.conf', 'w')
	config.set('CONFIGURATION', 'modo_actual', '3')
	if config['CONFIGURATION']['application_on'] == '0':
		config.set('CONFIGURATION', 'application_on', '1')
		if int(config['CONFIGURATION']['alerts']) == 0:
			try:
				stop_process()
			except:
				print('strnotprocess')
	config.write(configfile)
	configfile.close()
	if os.system('prime-select query') == 0:
		graphicsBefore = subprocess.getoutput('prime-select query')
	if cambiar_modo('maximorendimiento', user) == True:
		indicator.set_icon_full(MAX_PERFORMANCE, 'Icon max performance')
		if os.system('prime-select query') == 0:
			graphicsAfter = subprocess.getoutput('prime-select query')
			if graphicsBefore != graphicsAfter:
				rebootNvidia()
	else:
		print(_('strpasswordwrong'))
		configfile = open(user + '/.config/slimbookbattery/slimbookbattery.conf', 'w')
		config.set('CONFIGURATION', 'modo_actual', modoAnterior)
		config.write(configfile)
		configfile.close()

def modo_avanzado(self):
	self.set_sensitive(False)
	preferences_dialog = preferences.PreferencesDialog()
	preferences_dialog.set_modal(True)
	resultado = preferences_dialog.run()
	if resultado == Gtk.ResponseType.ACCEPT:
		preferences_dialog.close_ok()
		config.read(user + '/.config/slimbookbattery/slimbookbattery.conf')
		if int(config['CONFIGURATION']['application_on']) == 0 and int(config['CONFIGURATION']['alerts']) == 1:
			try:
				stop_process()
			except:
				print('strnotprocess')
			start_process(None)
			indicator.set_icon_full(DISABLED, 'Icon disabled')
		elif int(config['CONFIGURATION']['application_on']) == 0 and int(config['CONFIGURATION']['alerts']) == 0:
			try:
				stop_process
			except:
				print(_('strnotprocess'))
			indicator.set_icon_full(DISABLED, 'Icon disabled')
		elif int(config['CONFIGURATION']['application_on']) == 1 and int(config['CONFIGURATION']['alerts']) == 1:
			#Se para el proceso, si lo hay, y se vuelve a iniciar ya que sino lo hacemos en caso de que el proceso ya este corriendo pues se duplicarian los procesos.
			try:
				stop_process()
			except:
				print(_('strnotprocess'))
			start_process(None)
			if config['CONFIGURATION']['modo_actual'] == '1':
				indicator.set_icon_full(ENERGY_SAVING, 'Icon energy saving')
			elif config['CONFIGURATION']['modo_actual'] == '2':
				indicator.set_icon_full(EQUILIBRADO, 'Icon balanaced')
			elif config['CONFIGURATION']['modo_actual'] == '3':
				indicator.set_icon_full(MAX_PERFORMANCE, 'Icon max performance')
		elif int(config['CONFIGURATION']['application_on']) == 1 and int(config['CONFIGURATION']['alerts']) == 0:
			try:
				stop_process
			except:
				print(_('strnotprocess'))
			if config['CONFIGURATION']['modo_actual'] == '1':
				indicator.set_icon_full(ENERGY_SAVING, 'Icon energy saving')
			elif config['CONFIGURATION']['modo_actual'] == '2':
				indicator.set_icon_full(EQUILIBRADO, 'Icon balanced')
			elif config['CONFIGURATION']['modo_actual'] == '3':
				indicator.set_icon_full(MAX_PERFORMANCE, 'Icon max performance')
	else:
		#Comprueba el archivo de configuración para ver si application_on a pasado a 0, esto solo ocurrirá cuando se restablezcan los valores por defecto de General y de esta forma
		#se puede comprobar si ha sido así y parar el proceso, parar tlp y cambiar el icono.
		#Si el usuario le diese a cancelar y application_on estuviese ya en 0, no sucedería nada anormal puesto que va a intentar parar un proceso que ya estaba parado y caerá en
		#except y como el icono ya esta en disabled no cambiaría.
		config.read(user + '/.config/slimbookbattery/slimbookbattery.conf')
		if int(config['CONFIGURATION']['application_on']) == 0 and int(config['CONFIGURATION']['alerts']) == 1:
			try:
				stop_process()
			except:
				print(_('strnotprocess'))
			start_process(None)
			indicator.set_icon_full(DISABLED, 'Icon disabled')
		elif int(config['CONFIGURATION']['application_on']) == 0 and int(config['CONFIGURATION']['alerts']) == 0:
			try:
				stop_process()
			except:
				print(_('strnotprocess'))
			indicator.set_icon_full(DISABLED, 'Icon disabled')
	
	self.set_sensitive(True)
	preferences_dialog.hide()
	preferences_dialog.destroy()

def modo_apagado(val):
	config.read(user + '/.config/slimbookbattery/slimbookbattery.conf')
	modo_actual = int(config['CONFIGURATION']['modo_actual'])
	if modo_actual == 1:
		modo = "ahorrodeenergia"
	elif modo_actual == 2:
		modo = "equilibrado"
	elif modo_actual == 3:
		modo = "maximorendimiento"

	configfile = open(user + '/.config/slimbookbattery/slimbookbattery.conf', 'w')
	config.set('CONFIGURATION', 'application_on', '0')
	config.write(configfile)
	configfile.close()

	if os.system('prime-select query') == 0:
		graphicsBefore = subprocess.getoutput('prime-select query')

	if os.system("pkexec python3 /usr/share/slimbookbattery/slimbookbattery-changemode.pyc " + modo + " " + user + " 'stop'") == 0:
		if int(config['CONFIGURATION']['alerts']) == 0:
			try:
				stop_process()
			except:
				print(_('strnotprocess'))
		indicator.set_icon_full(DISABLED, 'Icon disabled')
		#Se vuelven a activar las animaciones del sistema
		if os.system('echo $XDG_CURRENT_DESKTOP | grep -i gnome') == 0:
			os.system('dconf write /org/gnome/desktop/interface/enable-animations true')
			os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-app-switch true')
			os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-window-launch true')

		if os.system('prime-select query') == 0:
			graphicsAfter = subprocess.getoutput('prime-select query')
			if graphicsBefore != graphicsAfter:
				rebootNvidia()
	else:		
		print(_('strpasswordwrong'))
		configfile = open(user + '/.config/slimbookbattery/slimbookbattery.conf', 'w')
		config.set('CONFIGURATION', 'application_on', '1')
		config.write(configfile)
		configfile.close()

#Se le pasa el nombre del archivo correspondiente a su modo de plan de energia para saber que archivo se tiene que utilizar en cada caso
#Se le pasa la ruta del usuario al archivo, ya que si se crease una variable en ese archivo nos indentificaría como el usuario root y no como el que intenta usar la aplicación
def cambiar_modo(modo, user):
	config.read(user + '/.config/slimbookbattery/slimbookbattery.conf')
	os.system('cp '+ user +'/.config/slimbookbattery/slimbookbattery.conf '+ user +'/.config/slimbookbattery/slimbookbattery_backup.conf')

	if modo == 'ahorrodeenergia':
		os.system('cp '+ user +'/.config/slimbookbattery/custom/ahorrodeenergia '+ user +'/.config/slimbookbattery/ahorrodeenergia_backup')
	elif modo == 'equilibrado':
		os.system('cp '+ user +'/.config/slimbookbattery/custom/equilibrado '+ user +'/.config/slimbookbattery/equilibrado_backup')
	elif modo == 'maximorendimiento':
		os.system('cp '+ user +'/.config/slimbookbattery/custom/maximorendimiento '+ user +'/.config/slimbookbattery/maximorendimiento_backup')

	if os.system("pkexec python3 /usr/share/slimbookbattery/slimbookbattery-changemode.pyc " + modo + " " + user + " 'start'") == 0:
		os.system('rm '+ user +'/.config/slimbookbattery/slimbookbattery_backup.conf')

		if modo == 'ahorrodeenergia':
			os.system('rm '+ user +'/.config/slimbookbattery/ahorrodeenergia_backup')
		elif modo == 'equilibrado':
			os.system('rm '+ user +'/.config/slimbookbattery/equilibrado_backup')
		elif modo == 'maximorendimiento':
			os.system('rm '+ user +'/.config/slimbookbattery/maximorendimiento_backup')

		#Se activan/desactivan las animaciones, según cómo lo tenga configurado el usuario para ese modo de ahorro
		if os.system('echo $XDG_CURRENT_DESKTOP | grep -i gnome') == 0:
			if modo == 'ahorrodeenergia':
				if config['SETTINGS']['ahorro_animations'] == '0':
					os.system('dconf write /org/gnome/desktop/interface/enable-animations false')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-app-switch false')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-window-launch false')
				else:
					os.system('dconf write /org/gnome/desktop/interface/enable-animations true')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-app-switch true')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-window-launch true')
			elif modo == 'equilibrado':
				if config['SETTINGS']['equilibrado_animations'] == '0':
					os.system('dconf write /org/gnome/desktop/interface/enable-animations false')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-app-switch false')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-window-launch false')
				else:
					os.system('dconf write /org/gnome/desktop/interface/enable-animations true')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-app-switch true')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-window-launch true')
			elif modo == 'maximorendimiento':
				if config['SETTINGS']['maxrendimiento_animations'] == '0':
					os.system('dconf write /org/gnome/desktop/interface/enable-animations false')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-app-switch false')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-window-launch false')
				else:
					os.system('dconf write /org/gnome/desktop/interface/enable-animations true')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-app-switch true')
					os.system('dconf write /org/gnome/shell/extensions/dash-to-panel/animate-window-launch true')

		return True
	else:
		os.system('rm '+ user +'/.config/slimbookbattery/slimbookbattery.conf')
		os.system('cp '+ user +'/.config/slimbookbattery/slimbookbattery_backup.conf '+ user +'/.config/slimbookbattery/slimbookbattery.conf')
		os.system('rm '+ user +'/.config/slimbookbattery/slimbookbattery_backup.conf')

		if modo == 'ahorrodeenergia':
			os.system('rm '+ user +'/.config/slimbookbattery/custom/ahorrodeenergia')
			os.system('cp '+ user +'/.config/slimbookbattery/ahorrodeenergia_backup '+ user +'/.config/slimbookbattery/custom/ahorrodeenergia')
			os.system('rm '+ user +'/.config/slimbookbattery/ahorrodeenergia_backup')
		elif modo == 'equilibrado':
			os.system('rm '+ user +'/.config/slimbookbattery/custom/equilibrado')
			os.system('cp '+ user +'/.config/slimbookbattery/equilibrado_backup '+ user +'/.config/slimbookbattery/custom/equilibrado')
			os.system('rm '+ user +'/.config/slimbookbattery/equilibrado_backup')
		elif modo == 'maximorendimiento':
			os.system('rm '+ user +'/.config/slimbookbattery/custom/maximorendimiento')
			os.system('cp '+ user +'/.config/slimbookbattery/maximorendimiento_backup '+ user +'/.config/slimbookbattery/custom/maximorendimiento')
			os.system('rm '+ user +'/.config/slimbookbattery/maximorendimiento_backup')

		return False

def rebootNvidia():
	pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(
			filename='/usr/share/slimbookbattery/images/normal.png',
			width=90,
			height=90,
			preserve_aspect_ratio=True)
	icon_MsgDialog = Gtk.Image.new_from_pixbuf(pixbuf)
	icon_MsgDialog.show()

	dialog = Gtk.MessageDialog(type= Gtk.MessageType.QUESTION,
		buttons= Gtk.ButtonsType.YES_NO,
		message_format=(_('strdialogtitle')))
	dialog.set_image(icon_MsgDialog)
	dialog.format_secondary_text(_('strdialogmessage'))
	response = dialog.run()
	if response == Gtk.ResponseType.YES:
		os.system('reboot')
	elif response == Gtk.ResponseType.NO:
		print(_('strsystemnotrestart'))

	dialog.destroy()

if __name__ == "__main__":
	if __file__.startswith('/usr') or os.getcwd().startswith('/usr'):
		sys.path.insert(1, '/usr/share/slimbookbattery')
	else:
		sys.path.insert(1, os.path.normpath(
			os.path.join(os.getcwd(), '../src')))
	import preferences
	signal.signal(signal.SIGINT, signal.SIG_DFL)
	main()
