#!/usr/bin/python
import gviz_api

#> ct
#               RegularSuper
#Candidate       Regular Super
#  barack obama    28864    41
#  mitt romney     10470   159
#  newt gingrich    1266    18

#first create the schema, explaining the columns and their types
description = [("candidate","string"),("Regular","number"),("Super","number")]

data=[]
for line in open('/home/qtw/public_html/data/regsuper.csv'):
    bits=line.split(',')
    #skip the header file since that is still hard-coded
    if bits[0]=='candidate': continue
    data.append((bits[0],int(bits[1]),int(bits[2])))

#create a DataTable object
data_table = gviz_api.DataTable(description)
data_table.LoadData(data)

#convert to JSON (could also send no parameters, this just demonstrates that you can re-order
json_str=data_table.ToJSon(columns_order=("candidate", "Regular", "Super"), order_by="Regular")

bar_template = """
<html>
  <head>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = new google.visualization.DataTable(%(json_str)s);


        var options = {
          title: 'Regular versus Super PAC',
          hAxis: {title: 'Candidates', titleTextStyle: {color: 'red'}}
        };

        var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>
""" 

#write an HTML file in your public_html directory
f=open('/home/qtw/public_html/code/exchart3.html','w')
f.write(bar_template % vars())
f.close()
