#!/usr/bin/python
"""
csv_plugin.py

This is in process in xrender.py until we work out packaging issues.
"""

import csv
import os
import shutil
import sys

import jsontemplate

class Error(Exception):
  pass

# See http://datatables.net/usage/
# CDN: http://www.asp.net/ajaxlibrary/CDNjQueryDataTables194.ashx

# TODO:
# - generate a different table ID for each one, and then style only that?
#   - I think you can generate the ID in the web roll.  That makes a lot more
#   sense, since it's dynamic.
#   - <div class="roll-part" id="part1"> 
# - don't want every plugin to hard code jquery.getScript
#   - would be nicer to present <elem js="http://" css="http://">

TABLE_TEMPLATE = jsontemplate.Template("""\

<link rel="stylesheet" type="text/css"
      href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css" />

<script type="text/javascript">
var dtjs="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js";

//$.getScript(dtjs, function() {
//  // NOTE: Is this inefficient?  When you have a lot of tables, it's doing
//  // everything.  Another approach is to generate a unique ID.  But user
//  // scripts might not have that benefit?
//
//  $('.data-table').dataTable();
//});

// Using Chrome dev tools, we can that the JS becomes a cache hit, while
// $.getScript() explicitly breaks caches.

$.ajax({
  url: dtjs,
  dataType: "script",
  cache: true,  // avoid loading every time
  success: function() {
    $('.data-table').dataTable();
  }
});

</script>

<table class="data-table" align="center">
  <thead>
    <tr> {.repeated section thead} <th>{@}</th> {.end} </tr>
  </thead>
  <tbody>
    {.repeated section rows}
      <tr> {.repeated section @} <td>{@}</td> {.end} </tr>
    {.end}
  </tbody>
</table>

<p>
  <a href="{orig_url|htmltag}">{orig_anchor}</a>
</p>
""", default_formatter='html')


PREVIEW_TEMPLATE = jsontemplate.Template("""\
<p>{basename} - {num_rows} rows</p>

<p><a href="{output}/full.html">Browse CSV</a></p>

<p><a href="{output}/{basename}">Download Original CSV</a></p>

""", default_formatter='html')



def RenderCsv(orig_rel_path, filename, contents):
  """
  Turn CSV into an HTML table.

  TODO: maximum number of rows.
  """
  lines = contents.splitlines()
  c = csv.reader(lines)
  d = {'rows': [], 'orig_url': orig_rel_path, 'orig_anchor': filename}

  for i, row in enumerate(c):
    #print 'R', row
    if i == 0:
      d['thead'] = row
    else:
      d['rows'].append(row)
  #print d
  return TABLE_TEMPLATE.expand(d), None


def main(argv):
  """Returns an exit code."""

  # Assume we're in the output dir
  input_path, output = argv[1:]

  os.mkdir(output)
  basename = os.path.basename(input_path)
  orig = os.path.join(output, basename)

  # Copy the original
  shutil.copy(input_path, orig)

  full_html = os.path.join(output, 'full.html')
  with open(full_html, 'w') as f:
    # TODO: write the full table here.  With JavaScript.
    f.write('hi')

  print output  # finished the dirthe dir

  # This

  html = output + '.html'

  with open(html, 'w') as f:
    d = {
        'num_rows': 5,
        'output': output,
        'basename': basename,
        }
    # TODO: check how many rows, and write head/tail, or full thing.
    f.write(PREVIEW_TEMPLATE.expand(d))

  print html  # wrote html

  return 0


if __name__ == '__main__':
  try:
    sys.exit(main(sys.argv))
  except Error, e:
    print >> sys.stderr, e.args[0]
    sys.exit(1)


@@ -1783,67 +1783,8 @@
 ble%3E
-%0A%0A%3Cp%3E%0A  %3Ca href=%22%7Borig_url%7Chtmltag%7D%22%3E%7Borig_anchor%7D%3C/a%3E%0A%3C/p%3E
 %0A%22%22%22
@@ -2050,55 +2050,78 @@
 %0A%0A%0A%0A
-def RenderCsv(orig_rel_path, filename, contents
+# TODO: avoid loading the entire thing in memory?%0Adef ParseAndRender(f
 ):%0A 
@@ -2199,40 +2199,8 @@
 %22%22%22%0A
-  lines = contents.splitlines()%0A
   c 
@@ -2216,13 +2216,9 @@
 der(
-lines
+f
 )%0A  
@@ -2236,60 +2236,8 @@
 : %5B%5D
-, 'orig_url': orig_rel_path, 'orig_anchor': filename
 %7D%0A%0A 
@@ -2365,19 +2365,8 @@
 ow)%0A
-  #print d%0A
   re
@@ -2398,15 +2398,8 @@
 d(d)
-, None%0A
 %0A%0Ade
@@ -2758,60 +2758,73 @@
     
-# TODO: write the full table here.  With JavaScript.
+with open(input_path) as infile:%0A      h = ParseAndRender(infile)
 %0A   
@@ -2836,12 +2836,9 @@
 ite(
-'hi'
+h
 )%0A%0A 
@@ -2870,23 +2870,16 @@
  the dir
-the dir
 %0A%0A  # Th

Write HTML table.