#!/usr/bin/ruby

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={};"
  
  (Dir.glob("./*/r.json") + ["./tm.json"]).each do |file|
    contents = open(file, 'r') {|f| f.read}.gsub("\n","")
    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

  ['browser_not_supported_template.html', 'player_template.html', 'time_warp_composer.html', "annotation_editor.html"].each do |file|
    contents = open(file, 'r') {|f| f.read}
    contents = contents.gsub('\\', '\\\\').gsub("\n",'\\n').gsub("\r","").gsub('"','\\"');
    # Hack to fix projection.  Remove this once Randy fixes the new generation path
    out.puts "cached_ajax['#{file}']=\"#{contents}\";"
    puts "Added #{file} (json quoted, #{contents.size} bytes)"
  end
end

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