#!/usr/bin/ruby

# This script is run by the Time Machine Creator software. Do not run this on your own unless you know what you are doing.

current_script_dir = File.dirname(__FILE__);
Dir.chdir(current_script_dir)

outfile = "ajax_includes.js"

puts "Creating #{outfile}";

open("#{outfile}.tmp", "w") do |out|
  out.puts "// Autogenerated by update_ajax_includes.rb #{Time.now}"
  out.puts "cached_ajax={};"

  # Pull dataset json info (tm.json and r.json from the videoset directory)
  (Dir.glob("./*/r.json") + ["./tm.json"]).each do |file|
    contents = open(file, 'r') {|f| f.read}.gsub("\n", "")
    # Legacy code. If old naming scheme found, convert it.
    contents = contents.gsub("lower-right-lat", "south");
    contents = contents.gsub("lower-right-lon", "east" );
    contents = contents.gsub("upper-left-lat" , "north");
    contents = contents.gsub("upper-left-lon" , "west" );
    out.puts "cached_ajax['#{file}']=#{contents};"
    puts "Added #{file} (literal, #{contents.size} bytes)"
  end

  # Pull templates
  ['templates/browser_not_supported_template.html', 'templates/player_template.html', 'templates/time_warp_composer.html', 'templates/annotation_editor.html'].each do |file|
    contents = open(file, 'r') {|f| f.read}
    contents = contents.gsub('\\', '\\\\').gsub("\n", '\\n').gsub("\r", "").gsub('"', '\\"');
    out.puts "cached_ajax['#{file}']=\"#{contents}\";"
    puts "Added #{file} (json quoted, #{contents.size} bytes)"
  end
end

File.rename "#{outfile}.tmp", outfile;
