#!/toc/home/edemaine/bin/python-beta

"""YAML -> JavaScript converter

Output style is based on that of the Data::JavaScript Perl module.

Distributed according to the MIT License; see also
        http://www.opensource.org/licenses/mit-license.php

Copyright (c) 1997-2006 Erik D. Demaine

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

"""

import os, sys
import yaml

def name2js (name):
  return name.replace (' ', '_')

def py2js (data, node = 'root', use_var = True, objects = {}):
  out = ''
  if use_var:
    out += 'var '
  out += node + ' = '
  if id (data) in objects:
    return out + objects[id (data)] + ';\n'
  objects[id (data)] = node
  if isinstance (data, list):
    out += 'new Array;\n'
    for i, item in enumerate (data):
      out += py2js (item, node + '[%d]' % i, False, objects)
  elif isinstance (data, dict):
    out += 'new Object;\n'
    for key, value in data.iteritems ():
      out += py2js (value, node + '.' + name2js (key), False, objects)
  elif isinstance (data, int) or isinstance (data, float):
    out += str (data) + ';\n'
  elif isinstance (data, str):
    out += repr (data) + ';\n'
  elif data is None:
    out += 'null;\n'
  else:
    raise ValueError ("py2js can't handle %r" % data)
  return out

def yaml2js (data):
  return py2js (yaml.load (data))

def yaml2js_file (input, output):
  input = file (input, 'r')
  output = file (output, 'w')
  output.write (yaml2js (input.read ()))
  output.close ()
  input.close ()

def main ():
  if len (sys.argv) not in (2, 3):
    sys.stderr.write ("Usage: yaml2js.py filename.yaml [filename.js]")
  input = sys.argv[1]
  if len (sys.argv) > 2:
    output = sys.argv[2]
  else:
    output = os.path.splitext (input) [0] + '.js'
  yaml2js_file (input, output)

if __name__ == '__main__': main ()
