#!/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 base64
import optparse
import parse_deps
import sys
import os
import re

from generate_template_contents import generate_templates

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

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_standalone_timeline_view.py
*
*        Do not edit directly.
*/
"""

css_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_standalone_timeline_view.py
*
*        Do not edit directly.
*/
"""

py_warning_message = """#!/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. */
#
# WARNING: This file is generated by generate_standalone_timeline_view.py
#
#        Do not edit directly.
#
"""

def _sopen(filename, mode):
  if filename != '-':
    return open(filename, mode)
  return os.fdopen(os.dup(sys.stdout.fileno()), 'w')

def _get_input_filenames():
  return [os.path.join(srcdir, f)
          for f in ['base.js', 'tracing/standalone_timeline_view.js']]

def generate_css():
  filenames = _get_input_filenames()
  load_sequence = parse_deps.calc_load_sequence(filenames, srcdir)

  style_sheet_chunks = [css_warning_message, '\n']
  for module in load_sequence:
    for style_sheet in module.style_sheets:
      style_sheet_chunks.append("""%s\n""" % style_sheet.contents)

  # Borrowed from grit html_format.py.
  def InlineUrl(m):
    filename = m.group('filename')
    idx = filename.index('/images')
    filename = "%s%s" % (srcdir, filename[idx:])
    ext = filename[filename.rindex('.') + 1:]

    with open(filename, 'rb') as f:
      data = f.read();
    data = base64.standard_b64encode(data)

    return "url(data:image/%s;base64,%s)" % (ext, data)

  full_style_sheet = ''.join(style_sheet_chunks)
  # I'm assuming we only have url()'s associated with images
  return re.sub('url\((?P<quote>"|\'|)(?P<filename>[^"\'()]*)(?P=quote)\)',
                lambda m: InlineUrl(m),
                full_style_sheet)


def generate_js():
  filenames = _get_input_filenames()
  load_sequence = parse_deps.calc_load_sequence(filenames, srcdir)


  js_chunks = [js_warning_message, '\n']
  js_chunks.append("window.FLATTENED = {};\n")
  js_chunks.append("window.FLATTENED_RAW_SCRIPTS = {};\n")

  for module in load_sequence:
    for dependent_raw_script_name in module.dependent_raw_script_names:
      js_chunks.append("window.FLATTENED_RAW_SCRIPTS['%s'] = true;\n" %
        dependent_raw_script_name)
    js_chunks.append( "window.FLATTENED['%s'] = true;\n" % module.name)

  html_encoded = base64.b64encode(generate_templates())
  js_chunks.append("var templateData_ = window.atob('" +
                   html_encoded + "');\n");
  js_chunks.append("var templateElem_ = document.createElement('div');\n");
  js_chunks.append("templateElem_.innerHTML = templateData_;\n");
  js_chunks.append("while (templateElem_.hasChildNodes()) {\n");
  js_chunks.append("  document.head.appendChild(" +
                   "templateElem_.removeChild(templateElem_.firstChild));\n");
  js_chunks.append("}\n\n");

  for module in load_sequence:
    js_chunks.append(module.contents)
    js_chunks.append("\n")

  return ''.join(js_chunks)

def main(args):
  parser = optparse.OptionParser(
    usage="%prog --js=<filename> --css=<filename>",
    epilog="""
A script to takes all of the javascript and css files that comprise trace-viewer
and merges them together into two giant js and css files, taking into account
various ordering restrictions between them.
""")
  parser.add_option("--js", dest="js_file",
                    help="Where to place generated javascript file")
  parser.add_option("--css", dest="css_file",
                    help="Where to place generated css file")
  options, args = parser.parse_args(args)

  if not options.js_file and not options.css_file:
    sys.stderr.write("ERROR: Must specify one of --js=<filename> or "
        "--css=<filename>\n\n")
    parser.print_help()
    return 1

  if options.js_file:
    with _sopen(options.js_file, 'w') as f:
      f.write(generate_js())

  if options.css_file:
    with _sopen(options.css_file, 'w') as f:
      f.write(generate_css())

  return 0

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