#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import optparse
import parse_deps
import sys
import os

srcdir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../src"))

FILES_TO_IGNORE = ["about_tracing.js"]

js_warning_message = (
"""// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * WARNING: This file is generated by generate_deps_js_contents.py
 *
 *        Do not edit directly.
 */
""")

def generate_deps_js():
  all_filenames = []
  for dirpath, dirnames, filenames in os.walk(srcdir):
    for f in filenames:
      all_filenames.append(os.path.join(dirpath, f))
  filenames = [x for x in all_filenames if
               os.path.splitext(x)[1] == ".js"]

  filenames = [os.path.relpath(x) for x in filenames]
  filenames = [x for x in filenames
               if x not in FILES_TO_IGNORE]

  if "deps.js" in filenames:
    filenames.remove("deps.js")

  load_sequence = parse_deps.calc_load_sequence(filenames)

  chunks = [js_warning_message]
  for module in load_sequence:
    for dependent_module_name in module.dependent_module_names:
      chunks.append("base.addModuleDependency(\n    '%s',\n    '%s');\n" % (
          module.name, dependent_module_name));

    for style_sheet in module.style_sheets:
      chunks.append("base.addModuleStylesheet(\n    '%s',\n    '%s');\n" % (
          module.name, style_sheet.name));

  result = "".join(chunks)
  return result

def is_out_of_date():
  olddir = os.getcwd()
  try:
    os.chdir(srcdir)

    o = open(os.path.join(srcdir, "deps.js"), 'r')
    existing_deps_js = o.read()
    o.close()

    result_js = generate_deps_js()

    if result_js != existing_deps_js:
      return True

  finally:
    os.chdir(olddir)
  return False


def main(args):
  parser = optparse.OptionParser()
  options, args = parser.parse_args(args)

  olddir = os.getcwd()
  try:
    os.chdir(srcdir)

    try:
      deps_js = generate_deps_js()
    except parse_deps.DepsException, ex:
      sys.stderr.write("Error: %s\n\n" % str(ex))
      return 255

    o = open(os.path.join(srcdir, "deps.js"), 'w')
    o.write(deps_js)
    o.close()

  finally:
    os.chdir(olddir)

  return 0

if __name__ == "__main__":
  sys.exit(main(sys.argv))
