from jinja2 import Template
from os.path import join
import json
import codecs

def do():
    data = json.load(open("chronoPeople.json"))
    people = json.load(open("people.json"))
    i = 1
    for d in data:
        d['serial'] = i
        i += 1
        d['bios'] = []
        for p in d['people']:
            if people.has_key(p):
                d['bios'].append({
                    'name': p,
                    'bio': people[p]
                })
            else:
                print "Error: %d, %s" % (d['serial'], p,)

    t = Template(open("template.html").read())
    s = t.render({'files': data})
    out = codecs.open("out.html", "w", encoding="utf-8")
    out.write(s)
    out.close()

def peoplejson():
    f = open("people.txt")
    o = ''
    for line in f:
        o = o + line.strip().replace("\n", "") + ",\n"
    out = open("people.json", "w")
    d = "{" + o[0:-1] + "}"
    print d
    out.write(d)
    out.close()
#    out.write(json.dumps(json.loads(d), indent=2))
#    out.close()
        

def doPersons():
    radias = json.load(open("chronoPrint.json"))
    people = json.load(open("people.json"))
    for r in radias:
        r['people'] = []
        title = r['title']
        for p in people.keys():
            if title.find(p) != -1:
                r['people'].append(p)
    o = open("chronoRadiaPeople.json", "w")
    o.write(json.dumps(radias, indent=2))
    o.close()
    

def radiaToChrono():
    radias = json.load(open("radiaPeople.json"))
    chronos = json.load(open("chronoPrint.json"))
    x = 0
    for r in radias:
        chronos[x]['people'] = radias[x]['people']
        x += 1
    print x
    out = open("chronoPeople.json", "w")
    out.write(json.dumps(chronos))
    out.close()
    

def addIndexes():
    people = json.load(open("chronoRadiaPeople.json"))
    x = 0
    short = []
    for p in people:
        index = x
        p['index'] = x
        x += 1
        if len(p['people']) == 0:
            short.append({
                'index': index,
                'title': p['title'],
                'people': []
            })
    out = open("chronoRadiaPeopleIndexed.json", "w")
    out.write(json.dumps(p, indent=2))
    out.close()
    out2 = open("peopleToBeFixed.json", "w")
    out2.write(json.dumps(short, indent=2))
    out2.close()

