import json


def SequentiallyLoadJavascript(files, selector='', closure=''):
  """Produces javascriprt to sequentially load all files.

  Example
     SequentiallyLoadJavascript(
        files=['jquery.js', 'jquery-deathstar.js'],
        selector='#msgid',
        closure='ActivateDeathStar()')

  Args:
     files: iterable of javascript urls. Will be loaded
     in the order they were received. If any file fails to load
     any consequent javascript will not execute (and neither will
     closure).
     selector: CSS selector for element to display "pending message".
     closure: will be run after all files have been loaded.

  Returns:
     the string with a valid javascript that accomplishes the loading.
  """

  # JSON produces valid javascript literals representing the array.
  selector_as_js_literal = json.dumps(selector)
  files_as_js_literal = json.dumps(files)

  # wrap closure in an anonymous function
  wrapped_closure = 'function(){%s}' % closure

  result = ('colab.util.sequentiallyLoadJavascript(%s, %s, %s)' %
            (files_as_js_literal, selector_as_js_literal, wrapped_closure))
  return result