#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import json
import optparse

import jsontemplate


usage = "usage: %prog [--json] datafile.json [--template] templatefile"
parser = optparse.OptionParser(usage=usage)

parser.add_option(
    "--json",
    dest="json",
    help="optional commandline flag to identify the json datafile to be used"
)

parser.add_option(
    "--template",
    dest="template",
    help="optional commandline flag to identify the template file to be used"
)

(options, args) = parser.parse_args()

jsonfile = ""
templatefile = ""

if options.json and options.template:
    jsonfile = options.json
    templatefile = options.template
else:
    if len(args) < 2:
        parser.error("need both a template and json data file specified")
    jsonfile = args[0]
    templatefile = args[1]


data_f = open(jsonfile, "rb")
data = json.load(data_f)
data_f.close()

template_f = open(templatefile, "rb")
template_d = template_f.read()
template_f.close()
template = template_d.decode('utf-8')

renderdata = jsontemplate.expand(template, data)
print renderdata.encode('utf-8')

