#!/usr/bin/env python

# This file is part of Window-Switch.
# Copyright (c) 2009-2013 Antoine Martin <antoine@nagafix.co.uk>
# Window-Switch is released under the terms of the GNU GPL v3

import appindicator			#@UnresolvedImport
import gobject

from winswitch.consts import APPLICATION_NAME
from winswitch.util.paths import ICON_DIR
from winswitch.util.common import visible_command
from winswitch.ui import icons
from winswitch.ui.tray_util import BaseTray

ATTENTION_ICON = "winswitch_attention"

class AppIndicatorTray(BaseTray):
	"""
	Tray implementation using Ubuntu's appindicator..
	The icons we use must be registered with the system's icon theme,
	because using absolute paths only works in later versions:
	https://bugs.launchpad.net/indicator-application/+bug/668375
	Also set_label() was added later on...
	"""

	def __init__(self, popup_menu, activate_menu, exit_cb, ask_quit, default_icon_name):
		BaseTray.__init__(self, popup_menu, activate_menu, exit_cb, ask_quit, default_icon_name)

	def setup_widget(self):
		self.tray_widget = appindicator.Indicator(APPLICATION_NAME,
							self.get_icon_filename(self.default_icon_name), appindicator.CATEGORY_APPLICATION_STATUS)
		if hasattr(self.tray_widget, "set_icon_theme_path"):
			self.tray_widget.set_icon_theme_path(ICON_DIR)
		self.tray_widget.set_attention_icon(ATTENTION_ICON)
		self.set_icon(self.default_icon_name)

	def get_icon_filename(self, icon_name):
		icon = icons.get(self.default_icon_name)
		return	icon.full_path_to_icon_file

	def close(self):
		self.hide_appindicator()

	def ready(self):
		self.show_appindicator()

	def hide_appindicator(self):
		self.sdebug()
		self.tray_widget.set_status(appindicator.STATUS_PASSIVE)

	def set_label(self, label):
		if hasattr(self.tray_widget, "set_label"):
			self.tray_widget.set_label(label)

	def show_appindicator(self):
		self.sdebug()
		self.set_label("")
		self.tray_widget.set_status(appindicator.STATUS_ACTIVE)

	def request_attention(self, message, delay):
		self.sdebug(None, message, delay)
		self.set_label(visible_command(message, max_len=24))
		self.tray_widget.set_status(appindicator.STATUS_ATTENTION)
		gobject.timeout_add(int(delay*1000), self.show_appindicator)

	def set_menu(self, menu):
		self.tray_widget.set_menu(menu)

	def set_icon(self, icon_name):
		self.tray_widget.set_icon(icon_name)
