
import ast

from pyxc.importing import SourcePath, orderedModules
from pyxc.transforming import Transformer
from pyxc.util import topLevelNamesInBody

import pj.js_ast
import pj.transformations


#### Code to Code
def codeToCode(py):
    t = Transformer(pj.transformations, pj.js_ast.JSStatements)
    jsAst = t.transformCode(py)
    js = '%s\n%s' % ('\n'.join(t.snippets), str(jsAst))
    return js


#### Build Bundle
def buildBundle(mainModule, path=None):
    
    assert path
    
    t = Transformer(pj.transformations, pj.js_ast.JSStatements)
    sourcePath = SourcePath(path)
    modules = orderedModules(sourcePath, mainModule)
    
    jsArr = []
    topLevelNames = set()
    for module in modules:
        codePath = sourcePath.pathForModule(module)
        with open(codePath, 'rb') as f:
            py = f.read()
            
            # Load the top-level names and confirm they're distinct
            for name in topLevelNamesInBody(ast.parse(py).body):
                assert name not in topLevelNames
                topLevelNames.add(name)
            
            # py &rarr; js
            jsAst = t.transformCode(py)
            js = str(jsAst)
            jsArr.append(js)
    
    if len(topLevelNames) > 0:
        varJs = 'var %s;' % ', '.join(list(topLevelNames))
    else:
        varJs = ''
    
    js = '''(function(){
  %s
  %s
  %s
})();''' % (
                '\n'.join(t.snippets),
                varJs,
                '\n'.join(jsArr))
    
    return js



@@ -827,32 +827,149 @@
 ()%0A            %0A
+            if codePath.endswith('.js'):%0A                js = py%0A            %0A            else:%0A                %0A    
             # Lo
@@ -1028,24 +1028,28 @@
             
+  
+  
 for name in 
@@ -1101,24 +1101,28 @@
             
+    
 assert name 
@@ -1142,16 +1142,20 @@
 elNames%0A
+    
         
@@ -1190,33 +1190,41 @@
 me)%0A            
-%0A
+    %0A    
             # py
@@ -1242,24 +1242,28 @@
             
+  
+  
 jsAst = t.tr
@@ -1286,24 +1286,28 @@
             
+    
 js = str(jsA
@@ -1310,16 +1310,29 @@
 (jsAst)%0A
+            %0A
         

support inclusion of JavaScript files