#########################################################################
# pglauncher - An unoffical Launcher for the "Project: Gorgon" game     #
# Copyright (C) 2014  Alexander Schlarb                                 #
#                                                                       #
# This program is free software: you can redistribute it and/or modify  #
# it under the terms of the GNU General Public License as published by  #
# the Free Software Foundation, either version 3 of the License, or     #
# (at your option) any later version.                                   #
#                                                                       #
# This program is distributed in the hope that it will be useful,       #
# but WITHOUT ANY WARRANTY; without even the implied warranty of        #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
# GNU General Public License for more details.                          #
#########################################################################

import argparse
import platform
import os
import sys
import traceback

from .progressbar import progressbar

import pglauncher.patcher
import pglauncher.launcher


class UI(pglauncher.patcher.PatcherCallbacks):
	def __init__(self):
		# Detect graphical environment without terminal window
		if hasattr(os, 'execlp') and 'DISPLAY' in os.environ and not 'TERM' in os.environ:
			# Try to re-execute process within terminal window (but tolerate failure)
			try:
				os.environ["TERM"] = "fake"
				os.execlp("x-terminal-emulator", "x-terminal-emulator", "-e", *sys.argv)
			except FileNotFoundError:
				pass
		
		# Progress bar used to draw the progress of the launcher
		self.progressbar = progressbar.ProgressBar('green', block='▓', empty='░')
	
	
	def run(self, argv):
		parser = argparse.ArgumentParser()
		parser.add_argument("--platform", "-p", dest="plat", action="store", default=platform.system().lower(),
				help="The target platform (defaults to the current platform, can be: windows, linux)")
		parser.add_argument("--no-launch", "-s", dest="launch", action="store_false", default=True,
				help="Do not launch application after the patching is complete")
		args = parser.parse_args(argv)
		
		self.should_launch = args.launch
		
		# Load patcher for the requested platform
		if args.plat == "linux":
			self.patcher = pglauncher.patcher.LinuxPatcher(self)
		elif args.plat == "windows":
			self.patcher = pglauncher.patcher.WindowsPatcher(self)
		else:
			parser.error("Target platform \"%s\" is not supported (use \"--platform\" to try a different platform)" % (args.plat))
		
		try:
			self.patcher.patch()
		except Exception as error:
			sys.stderr.write("\n")
			traceback.print_exception(type(error), error, error.__traceback__)
			sys.stderr.write("\n")
		
		input("Press enter to exit…")
	
	
	def handle_patcher_have_launcher_version(self, launcher_version):
		print(" • Launcher version: {}".format(launcher_version))
	
	def handle_patcher_have_game_version(self, game_version):
		print(" • Game version:  {}".format(game_version))
	
	def handle_patcher_have_welcome_message(self, welcome_message):
		pass
	
	def handle_patcher_progress_total(self, value):
		pass
	
	def handle_patcher_progress_current(self, value_part, value_file, message):
		# Update the progress bar
		self.progressbar.render(value_part * 100, message)
		
		if value_part == 1.0:
			# Clear the progress bar once the download is complete
			self.progressbar.clear()
	
	def handle_patcher_done(self):
		if not self.should_launch:
			return
		
		# Start game
		pglauncher.launcher.launch(self.patcher)
