#!/usr/bin/env python3

#
# Jasy - Web Tooling Framework
# Copyright 2010-2012 Zynga Inc.
#

# Import standard library stuff
import sys, os.path, json, logging

# Version check
if sys.version_info[0] < 3:
    sys.stderr.write("Jasy requires Python 3!\n")
    sys.exit(1)

# Include local Jasy into Python library path
basedir = os.path.join(os.path.dirname(sys.argv[0]), os.pardir)
if os.path.exists(os.path.join(basedir, "jasy")):
    sys.path.insert(0, basedir)
                
if len(sys.argv) == 1:
    sys.stderr.write("Missing job name\n")
    sys.exit(1)
    
supported = set(("api", "compress", "deps", "meta", "optimize", "tree"))
job = sys.argv[1]
if not job in supported:
    sys.stderr.write("Invalid job %s\n" % job)
    sys.exit(1)

logging.basicConfig(level=logging.DEBUG, format="%(message)s")

import jasy

from jasy.js.parse.Parser import parse
from jasy.js.parse.ScopeScanner import scan
from jasy.js.api.Data import ApiData
from jasy.js.output.Compressor import Compressor
from jasy.js.output.Optimization import Optimization
from jasy.core.Permutation import Permutation

import jasy.js.clean.Permutate
import jasy.js.clean.DeadCode
import jasy.js.clean.Unused

for fname in sys.argv[2:]:
    text = open(fname, encoding="utf-8").read()
    root = parse(text, fname)
    variables = scan(root)
    
    print(">>> File: %s" % fname)
    
    if job == "api":
        apidata = ApiData(fname, True)
        apidata.scanTree(root)
        print(apidata.export())
        
    elif job == "compress":
        print(Compressor().compress(root))
        
    elif job == "deps":
        if variables.modified:
            print("Exported Variables:")
            for name in sorted(variables.modified):
                print(" - %s" % name)

        if variables.shared:
            print("Accessed Globals:")
            for name in sorted(variables.shared):
                print(" - %s (%sx)" % (name, variables.shared[name]))

        if variables.packages:
            print("Accessed Packages:")
            for package in sorted(variables.packages):
                print(" - %s (%sx)" % (package, variables.packages[package]))        
        
    elif job == "meta":
        meta = MetaData(root)

        print("Name: %s" % meta.name)
        print("Requires: %s" % meta.requires)
        print("Optionals: %s" % meta.optionals)
        print("Breaks: %s" % meta.breaks)
        print("Assets: %s" % meta.assets)        
        
    elif job == "optimize":
        permutation = Permutation({ "debug": False })
        jasy.js.clean.Permutate.patch(root, permutation)
        
        jasy.js.clean.DeadCode.cleanup(root)
        variables = scan(root)
        jasy.js.clean.Unused.cleanup(root)
        
        Optimization("declarations", "blocks", "variables", "privates").apply(root)
        print(Compressor().compress(root))
        
    elif job == "tree":
        print(root.toXml())
    

