#!/bin/env python
#coding:utf-8
#
# th6 replay parser module.
# 
# Author: dl
# 
# License under Creative Commons License
# http://creativecommons.org/licenses/by-nc-sa/2.5/
#
import os, sys, string, binascii, struct

# get th6 replay info.
#
# param: 
#	[replay-filepath]
# return: 
#	array[date, player, char, score, rank, version. drop]
#	  kind of chars:
#	   ("ReimuA", "ReimuB", "MarisaA", "MarisaB")
#	  kind of ranks: 
#	   ("Easy","Normal","Hard","Lunatic","Extra")
#
# Notice.
# Now this script can't retreave "version" information from replay file.
# So we set empty string instead of version info to retArray.
# 
# Thanks to 28-769
# 
def TH6Replay_getReplayFileInfo(filepath):
	# for ms-windows
	try:
		import msvcrt
		msvcrt.setmode(0, os.O_BINARY)
		msvcrt.setmode(1, os.O_BINARY)
	except ImportError:
		pass
	
	# [date, player, char, score, rank, version, drop]
	retArray = ["", "", "", "", "", "", ""]
	
	fin = None
	dat = None
	try:
		fin = open(filepath, "rb")
		dat = fin.read(0x30)
	finally:
		if fin:
			fin.close()
	
	if len(dat) < 0x30:
		return retArray
	
	if dat[0:4] != "T6RP":
		return retArray
	
	# Decryption
	dat2 = ""
	mask = ord(dat[0x0e])
	for i in range(0x0f):
		dat2 += dat[i]
	for i in range(0x0f, len(dat)):
		dat2 += chr( (ord(dat[i]) + 0x100 - mask) & 0xff )
		mask = (mask + 0x07) & 0xff
	
	# check
	if ord(dat2[0x06]) >= 0x04 or ord(dat2[0x07]) >= 0x05:
		return retArray
	
	# raplay info
	date = dat2[0x10:0x10+8]
	name = dat2[0x19:0x19+8]
	char = ord(dat2[0x06])
	rank = ord(dat2[0x07])
	score = struct.unpack("L", dat2[0x24:0x24+4])[0]
	drop = struct.unpack("f", dat2[0x2c:0x2c+4])[0]
	
	# [date, player, char, score, rank, version, drop]
	date = trimNull(date)
	date = "20" + date[6:8] + "/" + date[0:2] + "/" + date[3:5]
	retArray[0] = trimNull(date)
	retArray[1] = trimNull(name)
	chars = ("ReimuA", "ReimuB", "MarisaA", "MarisaB")
	retArray[2] = chars[char]
	retArray[3] = str(score)
	levels = ("Easy","Normal","Hard","Lunatic","Extra")
	retArray[4] = levels[rank]
	retArray[5] = ""
	retArray[6] = "%5.3f" % drop
	return retArray

def trimNull(s):
	while(True):
		if(len(s) > 0):
			if(s[-1] == "\x00"):
				s = s[:-1]
			else:
				break
		else:
			break
	return s
# end
