#!/usr/bin/python

import sys
import os
import os.path

basedir = os.path.join(os.path.pardir, os.path.pardir, "sc2")
contentdir = os.path.join (basedir, "content")
srcdir = os.path.join (basedir, "src")

res_types=['--',
	   'GFXRES',
	   'FONTRES',
	   'MUSICRES',
	   'SNDRES',
	   'STRTAB',
	   'BINTAB',
	   'CONVERSATION',
	   'SHIP']

class ResEntry(object):
	def __init__(self, line_num, constant, pkg, inst, hfile, res_type, res_file):
		self.line_num = line_num
		self.hfile = hfile
		self.constant = constant
		self.package = int(pkg)
		self.instance = int(inst)
		self.int_type = res_types.index(res_type)
		self.res_type = res_type
		self.res_file = res_file
	def res_number(self):
		return res_encode (self.package, self.instance, self.int_type)
	def csv_line(self):
		return "%s,%d,%d,%s,%s,%s" % (self.constant,self.package, self.instance,
				self.hfile, self.res_type, self.res_file)

def res_encode(pkg, instance, t):
    return ((pkg & 0x7ff) << 21) | ((instance & 0x1FFF) << 8) | (t & 0xFF)

def res_encode_str (pkg, instance, t):
    return "0x%08xL" % res_encode (pkg, instance, t)

def read_csv (fname="resources.csv"):
	result = []
	linenum = 0
	for line in file(fname):
		linenum += 1
		# We allow hash comments, but it's not wise to have them in the official
		# list, since it may interfere with CSV importers.
		if '#' in line:
			line = line[:line.index('#')]
		line = line.strip()
		if len(line) > 0:
			data = [x.strip() for x in line.split (',')]
			if len(data) == 6:
				try:
					result.append(ResEntry(linenum, *data))
				except ValueError:
					print>>sys.stderr, "Warning: Illegal P/I/T in line %d" % linenum
			else:
				print>>sys.strderr, "Warning: Incorrect number of fields in line %d" % linenum
	return result

def get_headers(l):
	result = {}
	for res in l:
		result[res.hfile]=True
	names = result.keys()
	names.sort()
	return names
		
def lst_text(vals):
	result = []
	in_index = [x for x in vals]
	in_index.sort(lambda x,y: x.res_number() - y.res_number())
	for entry in in_index:
		result.append("%3d %3d %3d %s" % (entry.package, entry.instance, entry.int_type, entry.res_file))
	return result

def header_text(header, vals):
	result = ["/* This file was auto-generated by the gen_resfiles utility and",
		  "   should not be edited directly.  Modify the master resource list",
		  "   instead and regenerate. */",
		  ""]
	in_index = [x for x in vals if x.hfile == header]
	in_index.sort(lambda x,y: x.res_number() - y.res_number())
	for entry in in_index:
		result.append("#define %s %s" % (entry.constant, res_encode_str(entry.package, entry.instance, entry.int_type)))
	return result

def dump_values(data):
	keys = data.keys()
	keys.sort()
	for f in keys:
		print "Writing ",f
		outfile = file(f,"wt")
		for l in data[f]:
			print>>outfile, l
		outfile.close()

def collate_data(data):
	result = {}
	headers = get_headers(data)
	result[os.path.join(contentdir, 'uqm.lst')] = lst_text(data)
	for header in headers:
		result[os.path.join(srcdir, *(header.split('/')))] = header_text(header, data)
	return result

# The actual C infrastructure isn't here for this anymore, so we don't actually call dump_values.
if __name__=='__main__':
	data = collate_data(read_csv('int_res.csv'))
	for x in data[os.path.join(contentdir, 'uqm.lst')]:
		print x
