require 'optparse'
require 'json'

options = {texturepacker: 'TexturePacker'}
OptionParser.new do |opts|
  opts.banner = "Usage: batch.rb [options]"

  opts.on("-i", "--input [VALUE]", "Input files") do |v|
    options[:input] = v
  end
  opts.on("-o", "--output [VALUE]", "Output root path") do |v|
    options[:output] = v
  end
  opts.on("-t", "--texturepacker [VALUE]", "Texturepacker path, you need to install TexturePacker first.") do |v|
    options[:texturepacker] = v
  end
end.parse!

p options


def convert_json(input, output)
  ijson = JSON.parse(File.read(input))
  ojson = {stage:{w:0, h:0}, frames:[]}
  ijson["frames"].each do |f|
  	frame = f[1]["frame"]
  	size = f[1]["spriteSourceSize"]
  	d = {tx: frame["x"], ty: frame["y"], px: size["x"], py: size["y"], pw: size["w"], ph: size["h"]}
  	sourceSize = f[1]["sourceSize"]
  	ojson[:stage][:w] = sourceSize["w"] if (sourceSize['w'] > ojson[:stage][:w])
  	ojson[:stage][:h]= sourceSize["h"] if (sourceSize['h'] > ojson[:stage][:h])
  	ojson[:frames].push d
  end
  File.open(output, 'w'){|f| f.write JSON.generate(ojson)}
  ojson
end

ajson = {}
Dir.entries(options[:input]).select {|f| !File.directory? f and (f.end_with? '.swf' or f.end_with? '.png' or f.end_with? '.jpg')}.each do |file|
  name = File.basename(file, File.extname(file))
  path = File.absolute_path(file, options[:input])
  output = File.join(options[:output], name)
  cmd = "#{options[:texturepacker]}  --disable-rotation --algorithm \"Basic\" --basic-sort-by \"best\" --sheet \"#{output}-texture.png\" --data \"#{output}-data.json\" --format json --trim-sprite-names --max-width 8192 --max-height 8192 --allow-free-size \"#{path}\""
  p "path:#{name}  #{file}"
  #File.open('foo.txt', 'w') { |f| f.write(cmd) }
  `#{cmd}`
  ajson[name] = convert_json("#{output}-data.json", "#{output}-mapper.json")
  File.delete "#{output}-data.json"
end
File.open(File.join(options[:output], 'all-mapper.json'), 'w'){|f| f.write JSON.generate(ajson)}
puts "All texture exported!"