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

import gtk
import gettext
import sys
import os
import gobject
from config import *
import decoder as decoder


_ = gettext.gettext
trayicon = gtk.StatusIcon()
trayicon.set_from_icon_name('gCue2tracks')
win = gtk.Window(gtk.WINDOW_POPUP)
screen = win.get_screen()
#label1 = gtk.Label(str='None')
progressbar1 = gtk.ProgressBar()
progressbar2 = gtk.ProgressBar()

def _on__expose_event(window, _event):
	w, h = window.size_request()
	window.style.paint_flat_box(window.window,
								gtk.STATE_NORMAL, gtk.SHADOW_OUT,
								None, window, "tooltip",
								0, 0, w, h)
	return False

''' create a popup window each time tooltip is requested '''
win.set_border_width(1)
win.set_resizable(False)
win.set_app_paintable(True)
win.set_name('gtk-tooltips')
win.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_TOOLTIP)

win.set_events(gtk.gdk.POINTER_MOTION_MASK)
outtertipbox = gtk.VBox()
outtertipbox.pack_start(progressbar1, False, False, 1)
outtertipbox.pack_start(progressbar2, False, False, 1)
win.add(outtertipbox)
win.connect('expose-event', _on__expose_event)
outtertipbox.show_all()
#win.set_size_request(300, -1)

def notebook(widget,a,b):
	gobject.timeout_add(10, lambda: builder.get_object('close').grab_focus())

def bsavep(widget):

	def dialogdestroy(widget):
		dialog.destroy()

	def bsaveok(widget):
		path = dialog.get_filename()
		global builder
		if button == 'savefolder_preference_btn':
			builder.get_object('open_folder').set_text(path)
			set('open_folder', path)
		else:
			builder.get_object('tmp_dir').set_text(path)
			set('tmp_dir', path)
		dialog.destroy()

	button = gtk.Buildable.get_name(widget)
	pathglade = os.path.join(get('workdir'), 'ui/filechooserdialog.glade')
	builder = gtk.Builder()
	builder.set_translation_domain('gCue2tracks')
	builder.add_from_file(pathglade)
	dialog = builder.get_object('filechooserdialog1')
	dic = {'bsave_cancel': dialogdestroy, 'bsave_ok': bsaveok}
	builder.connect_signals(dic)
	dialog.set_current_folder(os.path.expanduser('~'))
	dialog.set_title(_('Select folder'))
	response = dialog.run()

def codec_btn(widget):
	def dialogdestroy(widget):
		dialog.destroy()
	def bsaveok(widget):
		path = dialog.get_filename()
		global builder
		builder.get_object(button[:-3]).set_text(path)
		set(button, path)
		dialog.destroy()
	button = gtk.Buildable.get_name(widget)
	pathglade = os.path.join(get('workdir'), 'ui/filechooserdialog.glade')
	builder = gtk.Builder()
	builder.set_translation_domain('gCue2tracks')
	builder.add_from_file(pathglade)
	dialog = builder.get_object('filechooserdialog1')
	dic = {'bsave_cancel': dialogdestroy, 'bsave_ok': bsaveok}
	builder.connect_signals(dic)
	dialog.set_current_folder(os.path.expanduser('~'))
	dialog.set_action(gtk.FILE_CHOOSER_ACTION_OPEN)
	dialog.set_title(_('Select file'))
	response = dialog.run()
	dialog.destroy()

def destroy(widget):
	map(lambda x: set(x, builder.get_object(x).get_text()), widgets)
	widgets_ = [
		'filename_filter', 'mp3advance', 'mp3_utf',
		'convert_cue', 'copy_image', 'show_systray', 'show_in_taskbar',
		'minimize_on_close']
	map(lambda x:set(x, builder.get_object(x).get_active()), widgets_)
	window = builder.get_object('preferences_window')
	window.hide()

def mp3_utf (widget):
	mutagen = True
	try: import mutagen.id3
	except ImportError:mutagen = False
	global builder
	if not mutagen and builder.get_object('mp3_utf').get_active():
		builder.get_object('mp3_utf').set_active(False)
		message = _('mid3v2 (from python-mutagen) is not found')
		decoder.show_dialog(message)

##### systray #################################################################

def calculate_pos(widget):
	MARGIN = 4
	if widget is not None:
		try:
			x, y = widget.window.get_origin()
			if widget.flags() & gtk.NO_WINDOW:
				x += widget.allocation.x
				y += widget.allocation.y
			height = widget.allocation.height
		except:
			_icon_screen, icon_rect, _icon_orient = widget.get_geometry()
			x = icon_rect[0]
			y = icon_rect[1]
			height = icon_rect[3]
	w, h = win.size_request()

	screen = win.get_screen()
	pointer_screen, px, py, _ = screen.get_display().get_pointer()
	if pointer_screen != screen:
		px = x
		py = y
	try:
		# Use the monitor that the systemtray icon is on
		monitor_num = screen.get_monitor_at_point(x, y)
	except:
		# No systemtray icon, use the monitor that the pointer is on
		monitor_num = screen.get_monitor_at_point(px, py)
	monitor = screen.get_monitor_geometry(monitor_num)

	try:
		# If the tooltip goes off the screen horizontally, realign it so that
		# it all displays.
		if (x + w) > monitor.x + monitor.width:
			x = monitor.x + monitor.width - w
		# If the tooltip goes off the screen vertically (i.e. the system tray
		# icon is on the bottom of the screen), realign the icon so that it
		# shows above the icon.
		if ((y + h + height + MARGIN) >
			monitor.y + monitor.height):
			y = y - h - MARGIN
		else:
			y = y + height + MARGIN
	except:
		pass
	try:
		return x, y
	except:
		#Fallback to top-left:
		return monitor.x, monitor.y

def tooltip_show_manually():
	if True:
		_pscreen, px, py, _mods = screen.get_display().get_pointer()
		_icon_screen, icon_rect, _icon_orient = trayicon.get_geometry()
		x = icon_rect[0]
		y = icon_rect[1]
		width = icon_rect[2]
		height = icon_rect[3]
		if px >= x and px <= x+width and py >= y and py <= y+height:
			if not win.get_property('visible'):
				#self.traytips._start_delay(self.trayicon)
				x, y = calculate_pos(trayicon)
				win.move(x, y)
				win.show_all()
		else:
			#self.traytips._remove_timer()
			win.hide()

def iterate_status_icon():
	if trayicon.get_visible():
		tooltip_show_manually()
	gobject.timeout_add(250, iterate_status_icon)

def preference_activate():
	global builder, widgets
	pathglade = os.path.join(get('workdir'), 'ui/preferences.glade')
	builder = gtk.Builder()
	builder.set_translation_domain('gCue2tracks')
	builder.add_from_file(pathglade)
	'''restore dialog state'''
	widgets_ = [
			'filename_filter', 'mp3advance', 'mp3_utf',
			'convert_cue', 'copy_image', 'show_systray', 'show_in_taskbar',
			'minimize_on_close']
	map(lambda x:builder.get_object(x).set_active(get(x)), widgets_)

	widgets = [
		'tmp_dir', 'format', 'ogg', 'mp3', 'flac', 'ape',
		'wavpack', 'wvunpack', 'open_folder', 'codepage']
	map(lambda x:builder.get_object(x).set_text(get(x)), widgets)

	window = builder.get_object('preferences_window')
	dic = {
		'destroy' : destroy, 'bsavep' : bsavep,
		'tmp_dir' : bsavep, 'notebook' : notebook, 'codec_btn' : codec_btn,
		'mp3_utf' : mp3_utf, 'show_systray' : show_systray,
		'minimize_on_close' : minimize_on_close,
		'show_in_taskbar' : show_in_taskbar
			}
	builder.get_object('show_in_taskbar').set_sensitive(get('show_systray'))
	builder.connect_signals(dic)
	window.show()

def window_state_event_cb(window, event):
	if event.changed_mask & gtk.gdk.WINDOW_STATE_ICONIFIED:
		if event.new_window_state & gtk.gdk.WINDOW_STATE_ICONIFIED:
			#Window was minimized
			decoder.win.hide()
			return True

def make_menu(event_button, event_time, data=None):
	menu = gtk.Menu()
	agr = gtk.AccelGroup()
	decoder.win.add_accel_group(agr)
	close_item = gtk.ImageMenuItem(gtk.STOCK_QUIT, agr)
	key, mod = gtk.accelerator_parse("Q")
	close_item.add_accelerator("activate", agr, key, mod, gtk.ACCEL_VISIBLE)
	#Append the menu items
	menu.append(close_item)
	#add callbacks
	close_item.connect_object('activate', close_app, 'Quit')
	#Show the menu items
	close_item.show()
	#Popup the menu
	menu.popup(None, None, None, event_button, event_time)

def close_app(data=None):
	write()
	gtk.main_quit()

def on_right_click(data, event_button, event_time):
	make_menu(event_button, event_time)

def show_window(widget):
	if decoder.win.get_property('visible') and \
										(decoder.win.iconify_initially == 0):
		decoder.win.hide()
	else:
		decoder.win.show_all()
		decoder.win.deiconify()
	decoder.win.set_property('skip-taskbar-hint', get('show_in_taskbar'))
	return True

def hide_window(win, event):
	if not get('show_systray'):
		win.iconify()
	else:
		win.hide()
	return True

def show_systray(widget):
	is_show_systray = builder.get_object('show_systray').get_active()
	trayicon.set_visible(is_show_systray)
	if not is_show_systray:
		builder.get_object('show_in_taskbar').set_active(False)
	builder.get_object('show_in_taskbar').set_sensitive(is_show_systray)

def minimize_on_close(widget):
	decoder.win = get('builder').get_object('mainWindow')
	if not builder.get_object('minimize_on_close').get_active():
		decoder.win.disconnect(decoder.handler_id_moc)
	else:
		decoder.handler_id_moc = decoder.win.connect('delete-event', hide_window)

def show_in_taskbar(widget):
	if not builder.get_object('show_in_taskbar').get_active():
			decoder.win.disconnect(decoder.handler_id)
	else:
		decoder.handler_id = decoder.win.connect('window-state-event',
													window_state_event_cb)
	decoder.win.set_property('skip-taskbar-hint', get('show_in_taskbar'))

def systray(builder):
	decoder.win = get('builder').get_object('mainWindow')
	if get('show_in_taskbar'):
		decoder.handler_id = decoder.win.connect('window-state-event',
													window_state_event_cb)
	trayicon.set_visible(get('show_systray'))
	trayicon.connect('activate', show_window)
	trayicon.connect('popup-menu', on_right_click)
	iterate_status_icon()

	if get('minimize_on_close'):
		decoder.handler_id_moc = decoder.win.connect('delete-event', hide_window)
