#!/usr/bin/python3
# -*- python -*-
#
# Copyright (C) 2000-2016 Christopher R. Gabriel <cgabriel@cgabriel.org>
#
# 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 2 of the License.

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject, GdkPixbuf

import sys, os, os.path, random

# FIXME: change with something based on the setup script
try:
	os.stat("cappuccino.grm")
	PLUGIN_DIR = "./"
except OSError:
	PLUGIN_DIR = "/usr/share/cappuccino/"

# text to see if polygen is available
if not os.access("/usr/games/polygen",os.X_OK):
	print ("Error: polygen must be installed")
	print ("See http://www.polygen.org")
	sys.exit(1)

# to be discussed
pipe_command = 'polygen %s' % os.path.join(PLUGIN_DIR, 'cappuccino.grm')

class CappuccinoSplash(Gtk.Window):
	def __init__(self):
		Gtk.Window.__init__(self)
		image = Gtk.Image()
		pixbuf = GdkPixbuf.Pixbuf.new_from_file(os.path.join(PLUGIN_DIR,\
                        'cappuccino.jpg'))
		image.set_from_pixbuf(pixbuf)
		self.add(image)


class Cappuccino(Gtk.Window):
	def __init__(self,title,speed=400):
		Gtk.Window.__init__(self)
		# our data
		self.cur_position = 0.0
		self.speed = speed
		self.waiting_message = "Work in progress"
		self.current_message = self.new_phrase()

		# set window stuff
		self.fullscreen()
		self.set_title = title

		#window's widgets
		self.w_vbox = Gtk.VBox()


		self.w_label = Gtk.Label()
		self.w_vbox.pack_start(self.w_label,True,True,40)

		self.w_scroll = Gtk.ScrolledWindow()
		self.w_scroll.set_shadow_type(Gtk.ShadowType.ETCHED_IN)
		self.w_scroll.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
		self.w_vbox.pack_start(self.w_scroll, True, True,100)

		self.w_text = Gtk.TextView()
		self.w_text.set_editable(False)
		self.w_scroll.add(self.w_text)

		self.w_align = Gtk.Alignment()
		self.w_align.set(0.5,0.5,0.5,0.0)
		self.w_vbox.pack_start(self.w_align, True, True, 0)

		self.progressbar = Gtk.ProgressBar()
		# the bar is reset upon startup
		self.progressbar.set_fraction(0.0)
		self.w_align.add(self.progressbar)
		#self.w_vbox.pack_start(self.progressbar,True,True)

		self.get_log_data()
		self.add(self.w_vbox)
		# timeout that starts it all
		self.timeouter = GObject.timeout_add(self.speed, self.update)
		self.log_timeouter = GObject.timeout_add(1000, self.update_log)

		# event handling. Add some key press events handlers!!
		self.connect("delete_event", self.delete_handler)
		self.connect("destroy_event", self.delete_handler)


	def delete_handler(self,obj,param):
		# remove the timeout upon delete or  destroy event!
		GObject.source_remove(self.timeouter)

	def get_log_data(self):
		p = os.popen("polygen -X 50 %s" % os.path.join(PLUGIN_DIR,"compileline.grm"))
		self.log = p.readlines()
		p.close()

	def update_log(self):

		# do the log!
		if len(self.log) < 1:
			self.get_log_data()
		buf = self.w_text.get_buffer()
		buf.insert_at_cursor(self.log.pop())
		self.w_text.set_buffer(buf)
		ha = self.w_scroll.get_vadjustment()
		ha.set_value(ha.get_upper())
		self.w_scroll.set_vadjustment(ha)
		return True

	def update(self):

		self.cur_position += random.random() / 5.0


		if self.cur_position > 1.2:
			self.cur_position = 0.0
			self.current_message = self.new_phrase()

		self.w_label.set_markup('<span foreground="black" size="x-large"><b>%s</b></span>' % (self.current_message))

		pos = (self.cur_position > 1 and 1 or self.cur_position)
		self.progressbar.set_fraction(pos)
		self.progressbar.set_text(str(int(100*pos))+" %")
		return True

	def new_phrase(self):
		p = os.popen(pipe_command,"r")
		phrase = p.read().strip()
		p.close()
		return phrase

def startup(par):
	par.destroy()
	app = Cappuccino(sys.argv[0])
	app.connect("delete_event", Gtk.main_quit)
	app.connect("destroy_event", Gtk.main_quit)
	app.show_all()


if __name__ == "__main__":
	Gtk.init_check()
	splash = CappuccinoSplash()
	splash.show_all()
	t = GObject.timeout_add(3000, startup, splash)
	Gtk.main()
