#!/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

from winswitch import __version_number__ as our_version, \
	__version__ as our_version_str
from winswitch.consts import DOWNLOAD_URL, CURRENT_VERSION_URL, APPLICATION_NAME
from winswitch.util.common import no_newlines
from winswitch.util.simple_logger import Logger
import platform
import sys
import thread

logger=Logger("version_check", log_colour=Logger.MAGENTA)

FAKE_NEW_VERSION = False or "--fake-new-version-available" in sys.argv

UNAME = platform.uname()

def version_update_check():
	""" do the version check in a separate thread """
	logger.slog()
	thread.start_new_thread(do_version_update_check, ())

def go_download():
	import webbrowser
	webbrowser.open_new_tab("%s?%s" % (DOWNLOAD_URL, our_version_str))

def get_version_from_url(url):
	e = None
	try:
		logger.sdebug(None, url)
		import urllib2
		response = urllib2.urlopen(url)
		latest_version = no_newlines(response.read())
		latest_version_no = [int(y) for y in latest_version.split(".")]
		logger.slog("=%s" % latest_version, url)
		return	latest_version_no
	except urllib2.HTTPError, e:
		if hasattr(e, "code") and e.code==404:
			logger.slog(e, url)
			return	None
	except urllib2.URLError, e:
		logger.serror(e, url)
		return	None
	except Exception, e:
		pass
	logger.serr(None, e, url)
	return	None

def do_version_update_check():
	logger.sdebug()
	from winswitch.util.main_loop import callLater

	PLATFORM_FRIENDLY_NAMES = {"linux2" : "LINUX", "win" : "WINDOWS", "darwin" : "OSX"}
	platform_name = sys.platform
	if platform_name in PLATFORM_FRIENDLY_NAMES:
		platform_name = PLATFORM_FRIENDLY_NAMES.get(platform_name)
	arch = UNAME[5]				#could also have used: platform.architecture()[0]
	if arch and arch.find(" ")>0:
		arch = arch[:arch.find(" ")]

	latest_version_no = None
	if arch:
		latest_version_no = get_version_from_url("%s_%s_%s?%s" % (CURRENT_VERSION_URL, platform_name, arch, our_version_str))
	if not latest_version_no:
		latest_version_no = get_version_from_url("%s_%s?%s" % (CURRENT_VERSION_URL, platform_name, our_version_str))
	if not latest_version_no:
		latest_version_no = get_version_from_url("%s?%s" % (CURRENT_VERSION_URL, our_version_str))
	if latest_version_no is None:
		logger.slog("failed to contact version server, will try again in an hour")
		callLater(60*60, do_version_update_check)
	elif latest_version_no>our_version or FAKE_NEW_VERSION:
		logger.slog("newer version found! local version is %s and the latest version available is %s" % (our_version_str, latest_version_no))
		latest_version = ".".join([str(x) for x in latest_version_no])
		show_version_warning(latest_version)
	else:
		logger.slog("version %s is the latest, will check again in 24 hours" % our_version_str)
		callLater(60*60*24, do_version_update_check)

def show_version_warning(latest_version):
	logger.slog("new version available!")
	text = "You are currently using version %s," % our_version_str
	text += "\nversion %s is available for download." % latest_version
	text += "\n"
	text += "\nYou are encouraged to upgrade,"
	text += "\nthis should not affect your existing settings."
	text += "\n(You can turn off this version check in the configuration panel)"
	text += "\n"
	text += "\nDo you want to visit the download page now?"
	from winswitch.ui.dialog_util import get_dialog_util
	from winswitch.ui import icons
	import pygtk
	pygtk.require("2.0")
	import gtk
	get_dialog_util().ask("%s version %s is available" % (APPLICATION_NAME, latest_version),
						text, None, go_download,
						buttons = (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_YES, gtk.RESPONSE_OK),
						icon=icons.get("download"), UUID="version-check")

def main():
	from winswitch.util.main_loop import test_loop
	test_loop(version_update_check)
	return	0


if __name__ == "__main__":
	c = main()
	logger.slog("main()=%s" % c)
	sys.exit(c)
