#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Pyntor Components - component management for the Pyntor presentation program
# Copyright (C) 2006 Josef Spillner <josef@coolprojects.org>
# Published under GNU GPL conditions

import pygame
from pygame.locals import *

import imp
import sys
import os
import os.path
import getopt
import glob

import sdlnewstuffpyntor

version = "0.0+svn-20060225"

def componentfrompathname(pn):
	fn = pn.split("/")[-1]
	component = fn.replace(".py", "")
	return component

def list():
	scriptpos = os.path.join(os.getcwd(), __file__)
	scriptdir = os.path.dirname(scriptpos)
	installpath = os.path.join(scriptdir, "..", "share", "pyntor", "components")
	installpath = os.path.normpath(installpath)

	homepath = os.path.join(os.getenv("HOME"), ".pyntor", "components")

	componentlocs = {}
	componentfiles = {}
	componentfiles[installpath] = glob.glob(installpath + "/*.py")
	componentfiles[homepath] = glob.glob(homepath + "/*.py")
	componentfiles["components"] = glob.glob("components" + "/*.py")

	for componentdir in componentfiles:
		for pn in componentfiles[componentdir]:
			component = componentfrompathname(pn)
			componentlocs.setdefault(component, [])
			componentlocs[component].append(componentdir)

	fmt = ("Component", "Valid", "Doc", "Version", "Location(s)")
	print "%15s %5s %5s %7s %s" % fmt

	for component in componentlocs:
		first = 1
		for componentdir in componentlocs[component]:
			try:
				(fileobj, filename, desc) = imp.find_module(component, [componentdir])
				mod = imp.load_module(component, fileobj, filename, desc)
				fileobj.close()
			except:
				print "Error: Cannot load component", component, "in", componentdir
				mod = None
				continue

			valid = ""
			doc = ""
			version = "???"
			loc = componentdir

			if "component" in dir(mod):
				valid = "x"
			if "metainfo" in dir(mod):
				m = mod.metainfo
				if m.has_key("version"):
					version = m["version"]
			if "doc" in dir(mod):
				doc = "x"

			if first:
				fmt = (component, valid, doc, version, loc)
				first = 0
			else:
				fmt = ("", valid, doc, version, loc)
			print "%15s %5s %5s %7s %s" % fmt

			del sys.modules[component]

def doc(component):
	scriptpos = os.path.join(os.getcwd(), __file__)
	scriptdir = os.path.dirname(scriptpos)
	installpath = os.path.join(scriptdir, "..", "share", "pyntor", "components")
	installpath = os.path.normpath(installpath)

	homepath = os.path.join(os.getenv("HOME"), ".pyntor", "components")

	searchpaths = ["components", homepath, installpath]

	try:
		(fileobj, filename, desc) = imp.find_module(component, searchpaths)
		mod = imp.load_module(component, fileobj, filename, desc)
		fileobj.close()
	except:
		print "Error: Cannot load component", component
		mod = None
		return

	print "=== Documentation ==="
	if "doc" in dir(mod):
		print mod.doc
	else:
		print "Warning: component", component, "has no documentation"

	print "=== Meta information ==="
	if "metainfo" in dir(mod):
		m = mod.metainfo
		if m.has_key("author"):
			print "Author:", m["author"]
		if m.has_key("authoremail"):
			print "Author's email address:", m["authoremail"]
		if m.has_key("licence"):
			print "Licence agreement:", m["licence"]
		if m.has_key("version"):
			print "Version number:", m["version"]
		if m.has_key("homepage"):
			print "Homepage:", m["homepage"]
	else:
		print "Warning: component", component, "has no meta information"

	print "=== Parameters ==="
	if "parameters" in dir(mod):
		varargs = None
		for param in mod.parameters:
			(name, description, default) = param
			if not name:
				varargs = description
				continue
			xdefault = ""
			if default is not None:
				xdefault = "(default: '" + str(default) + "')"
			else:
				xdefault = "(required!)"
			print name + ":", description, xdefault
		if varargs:
			print
			print "Additional parameters can be used:", varargs
		if len(mod.parameters) == 0:
			print "(This component doesn't take any parameters.)"
	else:
		print "Warning: component", component, "has no parameters"

def update():
	pygame.init()
	pygame.display.set_caption("Get Hot New Pyntor Components!")

	fullscreen = 0

	if fullscreen:
		screen = pygame.display.set_mode((1024, 768), DOUBLEBUF)
		pygame.display.toggle_fullscreen()
	else:
		screen = pygame.display.set_mode((800, 600), DOUBLEBUF)

	pygame.display.flip()

	engine = sdlnewstuffpyntor.ghnsengine()

	engine.conf.providers = "http://pyntor.coolprojects.org/repository/providers.xml"
	engine.conf.installdir = ".pyntor/components"
	engine.conf.unpack = 0

	files = engine.gethotnewstuff("pyntor")

def main(command, arg):
	if command == "list":
		list()
	elif command == "doc":
		doc(arg)
	elif command == "update":
		update()
	else:
		print "Error: invalid command", command

if __name__ == "__main__":
	command = None
	arg = None

	try:
		longopts = ["help", "list", "version", "doc=", "update"]
		options = getopt.gnu_getopt(sys.argv[1:], "d:hlvu", longopts)
	except:
		print "Error:", sys.exc_info()[1]
		sys.exit(1)

	(options, arguments) = options

	for opt in options:
		(optkey, optval) = opt

		if optkey in ("-h", "--help"):
			print "Pyntor Components - component management tool"
			print "Copyright (C) 2006 Josef Spillner <josef@coolprojects.org>"
			print "Published under GNU GPL conditions"
			print ""
			print "Synopsis: pyntor-components [options]"
			print ""
			print "Options:"
			print "[-l | --list         ] List all components"
			print "[-d | --doc=component] Document component"
			print "[-u | --update       ] Get new components via GHNS"
			print "[-v | --version      ] Print Pyntor's version"
			print "[-h | --help         ] Display this help"
			sys.exit(0)
		elif optkey in ("-l", "--list"):
			command = "list"
		elif optkey in ("-d", "--doc"):
			command = "doc"
			arg = optval
		elif optkey in ("-u", "--update"):
			command = "update"
		elif optkey in ("-v", "--version"):
			print version
			sys.exit(0)

	if not command:
		print "Error: no command given"
		sys.exit(1)

	main(command, arg)

