#coding=utf8
import os
import urllib2
import json
import re
import sys
from os import listdir
from os.path import isfile, join

# For the unicode error
reload(sys)
sys.setdefaultencoding( "utf-8" )

base = "http://www.battlenet.com.cn/api/wow/character/"
guildbase = "http://www.battlenet.com.cn/api/wow/guild/"
dir = "data"+os.sep+"auctions"
#dir = "data" #For test
#keylist = ['ownerRealm', 'owner']
groups = ['alliance', 'horde', 'neutral']
#allcharlist = open('allcharlist', 'w')
#dir = "data/"
fix = ".json"
tardir = "data"

def Oneauction(File):
    s = set()
    if isfile(join(dir,File)):
        file = open(dir+os.sep+File, "r")
        content = json.load(file)
        for group in groups:
            for line in content[group]['auctions']:
                outline = line['ownerRealm'] + "/" + line['owner']
                #print outline
                oneline = base + outline + "?fields=guild"
                try:
                    character = json.load(urllib2.urlopen(oneline))
                    try:
                        name = character['guild']['name']
                        realmname = character['guild']['realm']
                        memberline = guildbase + realmname + "/" + name + "?fields=members"
                        s.add(memberline)
                        #print memberline
                    except KeyError, e:
                        print "Do not join a",  e
                except urllib2.URLError, e:
                    print "Character",  e.reason
        file.close()

    for i in s: 
        try:
            members = json.load(urllib2.urlopen(i))
            try:
                for onechar in members['members']:
                    if onechar['character']['level'] == 90:
                        charrealm = onechar['character']['realm']
                        charname = onechar['character']['name']
                        perline = base + charrealm + "/" + charname + "?fields=stats,items,professions,pvp,talnets,titles,audit"
                        targetdir = tardir + os.sep + charrealm + os.sep
                        if not os.path.exists(targetdir):
                            os.mkdir(targetdir)
                            print 'Successfully created directory', targetdir
                        file = open(targetdir+charrealm+"_"+charname+fix, "wb")
                        file.write(urllib2.urlopen(perline).read())
                        #allcharlist.write(perline)
            except KeyError, e:
                print "No member in this guild",  e
        except urllib2.URLError, e:
            print "Guild",  e.reason

Oneauction(sys.argv[1])
