#!/usr/bin/env python

from bs4 import BeautifulSoup
import glob
import json

#############################################
# Convert Hearthstone card data XML to JSON #
#############################################

__author__ = "Taylor Caldwell - http://github.com/rithms"
__copyright__ = "Copyright 2015, Taylor Caldwell"
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "Taylor Caldwell"
__email__ = "tcaldwel@nmsu.edu"
__status__ = "Production"
 
# EnumIds - Non-Boolean
enum_dict = {
    
	45 : "health",
	47 : "attack",
	48 : "cost",
	183 : "cardSet",
	184 : "cardTextInHand",
	185 : "cardName",
	187 : "durability",
	199 : "class",
	200 : "race",
	201 : "faction",
	202 : "cardType",
	203 : "rarity",
	251 : "attackVisualType",
	252 : "cardTextInPlay",
	268 : "devState",
	325 : "targetingArrowText",
	330 : "enchantmentBirthVisual",
	331 : "enchantmentIdleVisual",
	342 : "artistName",
	351 : "flavorText",
	365 : "howToGetThisGoldCard",
	364 : "howToGetThisCard",
	#377 : "unknownHasOnDrawEffect",
	#380 : "unknownBlackrockHeroes",
	#389 : "unknownDuneMaulShaman",
	#402 : "unknownIntenseGaze",
	#401 : "unknownBroodAffliction"
}

# EnumIds - Boolean
bool_dict = {

	32 : "Trigger Visual",
	114 : "elite",	
	321 : "collectible",
	189 : "Windfury",
	190 : "Taunt",
	191 : "Stealth",
	192 : "Spell Power",
	194 : "Divine Shield",
	197 : "Charge",
	205 : "Summoned",
	208 : "Freeze",
	212 : "Enrage",
	215 : "Overload",
	217 : "Deathrattle",
	218 : "Battlecry",
	219 : "Secret",
	220 : "Combo",
	240 : "Can't Be Damaged",
	293 : "Morph",
	335 : "Invisible Deathrattle",
	338 : "One Turn Effect",
	339 : "Silence",
	340 : "Counter",
	349 : "Immune To Spell Power",
	350 : "Adjacent Buff",
	361 : "Heal Target",
	362 : "Aura",
	363 : "Poisonous",
	367 : "AI Must Play",
	370 : "Affected By Spell Power",
	388 : "Spare Part",
}

# Card Class IDs
class_dict = {

	0 : "Developer",
	2 : "Druid",
	3 : "Hunter",
	4 : "Mage",
	5 : "Paladin",
	6 : "Priest",
	7 : "Rogue",
	8 : "Shaman",
	9 : "Warlock",
	10 : "Warrior",
	11 : "Dream"
}

# Card Set IDs
set_dict = {

	2 : "Basic",
	3 : "Classic",
	4 : "Reward",
	5 : "Missions",
	7 : "System",
	8 : "Debug",
	11 : "Promotion",
	12 : "Curse of Naxxramas",
	13 : "Goblin vs Gnomes",
	14 : "Blackrock Mountain",
	16 : "Credits"
}

# Card Type IDs
type_dict = {

	3 : "Hero",
	4 : "Minion",
	5 : "Spell",
	6 : "Enchantment",
	7 : "Weapon",
	10 : "Hero Power"
}

# Card Race IDs
race_dict = {

	14 : "Murloc",
	15 : "Demon",
	17 : "Mechanical",
	20 : "Beast",
	21 : "Totem",
	23 : "Pirate",
	24 : "Dragon"
}

# Card Faction IDs
faction_dict = {

	1 : "Horde",
	2 : "Alliance",
	3 : "Neutral"
}

# Card Rarity IDs
rarity_dict = {

	0 : "Developer",
	1 : "Common",
	2 : "Free",
	3 : "Rare",
	4 : "Epic",
	5 : "Legendary"
}

# Get the name of the corresponding enum ID
def get_name(enum_id, d):
	if enum_id in d:
		return d[enum_id]


for f in glob.glob('cardxml0/CAB-cardxml0/TextAsset/*.txt'):
	with open(f) as cardfile:
		file_name = f.split('/')[-1].split('.')[0]
		cardsoup = BeautifulSoup(cardfile.read(), features="xml")
 
	cards = cardsoup.find_all('Entity')
	json_dict = { 'data' : {} }
	for card in cards:
		card_id = card.get('CardID')
		json_dict['data'][card_id] = { 'id' : card_id, 'mechanics' : [] }
 
		tags = card.find_all('Tag')
		for tag in tags:
			enum_id = int(tag.get('enumID'))
			if(tag.get('type') == 'String'):
				enum_name = tag.text
			else:
				enum_name = tag.get('value')
			if enum_id in enum_dict:
				field = enum_dict[enum_id]
				if field == 'class':
					enum_name = get_name(int(enum_name), class_dict)
				elif field == 'cardSet':
					enum_name = enum_name = get_name(int(enum_name), set_dict)
				elif field == 'cardType':
					enum_name = get_name(int(enum_name), type_dict)
				elif field == 'race':
					enum_name = get_name(int(enum_name), race_dict)
				elif field == 'faction':
					enum_name = get_name(int(enum_name), faction_dict)
				elif field == 'rarity':
					enum_name = get_name(int(enum_name), rarity_dict)

				json_dict['data'][card_id][enum_dict[enum_id]] = enum_name

			elif enum_id in bool_dict:
				field = bool_dict[enum_id]
				if field == 'collectible' or field == 'elite':
					if enum_name == '1':
						json_dict['data'][card_id][field] = True
					elif enum_name == '0':
						json_dict['data'][card_id][field] = False
				else:
					if enum_name == '1':
						json_dict['data'][card_id]['mechanics'].append(field)

		for key in bool_dict:
			field = bool_dict[key]
			if field == 'collectible' or field == 'elite':
				if field not in json_dict['data'][card_id]:
					json_dict['data'][card_id][field] = False
	
		if not json_dict['data'][card_id]['mechanics']:
			del json_dict['data'][card_id]['mechanics']

	with open(file_name+'.json', 'w') as outfile:
		json.dump(json_dict, outfile, sort_keys=True)
 




