#!python
# -*- coding: utf-8 -*-

import Tkinter as tk
from PIL import ImageTk
import os
import sys
import warnings

import src.globalvar as globalvar
import src.screen as screen
import src.splash as splash

def songFinderGui():
	# Creat main window and splash icon
	fenetre = tk.Tk()
	fenetre.withdraw()
	nb_screen, screen1, screen2, screen1use = screen.number_screen()
	try:
		splashScreen = splash.Splash(fenetre, os.path.join(globalvar.chemin_root, 'icon.png'), 0, screen1)
		splashScreen.__enter__()
	except Exception as e:
		warnings.warn(str(e))

	# Compile cython file and cmodules
	if not globalvar.portable:
		try:
			import subprocess
			import distutils.spawn
			python = distutils.spawn.find_executable('python')
			if python:
				command = python + ' setup_precompil.py build_ext --inplace'
				proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
				out, err = proc.communicate()
				if out:
					print(out)
					print(err)
		except Exception as e:
			warnings.warn(str(e))

	import src.interface as interface

	# Get command line args for opening songs and sets
	fileIn = None
	if len(sys.argv) > 1:
		fileIn = sys.argv[1]

	# Set bar icon
	try:
		if os.name == 'posix':
			img = ImageTk.PhotoImage(file = os.path.join(globalvar.chemin_root, 'icon.png') )
			fenetre.tk.call('wm', 'iconphoto', fenetre._w, img)
		else:
			fenetre.iconbitmap( os.path.join(globalvar.chemin_root, 'icon.ico'))
	except Exception as e:
		warnings.warn(str(e))

	songFinder = interface.Interface(fenetre, screen1, fileIn)
	fenetre.title('Song Finder')
	fenetre.protocol("WM_DELETE_WINDOW", songFinder.quitter)

	# Set windows size
	fenetre.update_idletasks()
	fen_w = fenetre.winfo_reqwidth()
	fen_h = fenetre.winfo_reqheight()
	fenetre.minsize(fen_w, fen_h)
	fenetre.geometry( screen.get_size(fen_w, fen_h, screen1, 5) )
	fenetre.resizable(width=True, height=True)

	try:
		splashScreen.__exit__()
	except Exception as e:
		warnings.warn(str(e))
	fenetre.deiconify()
	fenetre.lift()
	fenetre.mainloop()

if __name__ == '__main__':
	songFinderGui()

