import os
import shlex
import posixpath

from c2c.recipe.closurecompile.goog import treescan
from c2c.recipe.closurecompile.goog import source

class DepsWriter(object):
    def __init__(self, buildout, name, options):
        basedir = buildout['buildout']['directory']

        if options.get('root') is not None:
            raise zc.buildout.UserError("'root' option not supported yet.")

        if options.get('path_with_depspath') is not None:
            raise zc.buildout.UserError("'path_with_depspath' option not supported yet.")

        self.roots_with_prefix = options.get('root_with_prefix', '').split('\n')

        if options.get('output') is not None:
            self.output = os.path.join(basedir, options.get('output'))
        else:
            raise zc.buildout.UserError("'output' option is missing.")

    def install(self):
        path_to_source = {}

        for pairs in self.roots_with_prefix:
            root, prefix = shlex.split(pairs.replace('\\', '\\\\'))
            for path in treescan.ScanTreeForJsFiles(root):
                prefixed_path = os.path.join(prefix, os.path.relpath(path, root))
                # replace OS-specific path separators with URL-compatible forward slashes
                prefixed_path = prefixed_path.replace(os.sep, posixpath.sep)
                path_to_source[prefixed_path] = source.Source(source.GetFileContents(path))

        output = open(self.output, 'w')
        output.write('// This file was autogenerated by %s.\n' % __name__)
        output.write('// Please do not edit.\n')

        for path in sorted(path_to_source):
            js_source = path_to_source[path]
            if js_source.provides:
                line = (path, sorted(js_source.provides), sorted(js_source.requires))
                output.write("goog.addDependency('%s', %s, %s);\n"%line)

        return self.output

    update = install

