#!/usr/bin/env python

import zipfile
import argparse
import os
import lua
import sys
sys.path += ['/usr/share/wherpygo']
import gwc
import wherigo

args = argparse.ArgumentParser (description = 'Convert a wherigo source file to a wherigo cartridge, which can be played by wherpygo. The gwz argument must be a zipfile (usually using the extension gwz), or a directory with media and one lua source file, as they could appear in a gwz zipfile.')
args.add_argument ('gwz', help = 'gwz directory or zipfile to convert', type = str)
args.add_argument ('gwc', nargs = '?', default = None, help = 'gwc file to create', type = str)
args.add_argument ('--gametype', default = 'Puzzle', help = 'type of cartridge', type = str)
args.add_argument ('--author', default = 'Anonymous', help = 'creator of cartridge', type = str)
args.add_argument ('--description', default = 'No description set', help = 'description of cartridge', type = str)
args.add_argument ('--guid', default = '0', help = 'global uid for cartridge', type = str)
args.add_argument ('--name', default = None, help = 'cartridge name', type = str)
args.add_argument ('--latitude', default = 0, help = 'starting latitude', type = float)
args.add_argument ('--longitude', default = 0, help = 'starting longitude', type = float)
args.add_argument ('--altitude', default = 0, help = 'starting altitude', type = float)
args.add_argument ('--startdesc', default = 'No description set', help = 'description of starting location', type = str)
args.add_argument ('--url', default = 'about:blank', help = 'url for this cartridge', type = str)
args.add_argument ('--device', default = 'PocketPC', help = "device that this file says it's made for", type = str)
args.add_argument ('--version', default = '0', help = 'cartridge version', type = str)
args.add_argument ('--user', default = 'Monty Python', help = 'username for the player', type = str)
args.add_argument ('--completion_code', default = 'completion-code', help = 'completion code', type = str)
args.add_argument ('--icon', default = None, help = 'icon filename', type = str)
args.add_argument ('--splash', default = None, help = 'splash image filename', type = str)

a = args.parse_args ()
gwz = a.gwz
cartfile = os.path.splitext (gwz)[0]
target = a.gwc if a.gwc is not None else cartfile + os.extsep + 'gwc'
if a.name is None:
	a.name = cartfile

data = {}
code = None

if os.path.isdir (gwz):
	isdir = True
	names = os.listdir (gwz)
else:
	isdir = False
	z = zipfile.ZipFile (gwz, 'r')
	names = z.namelist ()

for n in names:
	ln = n.lower ()
	assert ln not in data
	if isdir:
		data[ln] = open (os.path.join (gwz, n), 'rb').read ()
	else:
		data[ln] = z.read (n)
	if os.path.splitext (ln)[1] == os.extsep + 'lua':
		assert code is None
		code = ln

assert code is not None
code = data.pop (code)

script = lua.lua ()
script.module ('Wherigo', wherigo)
script.run ('', 'Env', {
	'Platform': 'Python',
	'CartFolder': '/whatever',
	'SyncFolder': '/whatever',
	'PathSep': '/',
	'DeviceID': 'python-id',
	'Version': '2.11-compatible',
	'CartFilename': cartfile,
	'LogFolder': '/whatever',
	'Downloaded': 0,
	'Device': a.device})
class Cartdata:
	pass
cartdata = Cartdata ()
for key in ('gametype', 'author', 'description', 'guid', 'name', 'latitude', 'longitude', 'altitude', 'startdesc', 'url', 'device', 'version', 'user', 'completion_code'):
	setattr (cartdata, key, getattr (a, key))
cartridge = wherigo.ZCartridge ()
media = cartridge._getmedia (cartdata, script, code)
mdata = [None] * len (media)
for m in range (len (media)):
	assert media[m]._id == m + 1
	r = media[m].Resources._list ()
	if len (r) < 1:
		continue
	r = r[0]
	#t = r['Type'] Use?
	n = r['Filename']
	mdata[m] = data.pop (n.lower ())

if a.icon is not None:
	cartdata.icon = data.pop (a.icon)
if a.splash is not None:
	cartdata.splash = data.pop (a.splash)

if len (data) != 0:
	print 'ignoring unused media: %s.' % (', '.join (data.keys ()))

gwc.write_cartridge (target, cartdata, code, mdata)
