#!/usr/bin/env ruby
require 'mikunyan'
require 'mikunyan/decoders'
require 'fileutils'

opts = {:as_asset => false, :outputdir => nil, :sprite => false}
arg = nil
i = 0
while i < ARGV.count
    if ARGV[i].start_with?('-')
        case ARGV[i]
        when '--as-asset', '-a'
            opts[:as_asset] = true
        when '--outputdir', '-o'
            i += 1
            opts[:outputdir] = ARGV[i]
        when '--sprite', '-s'
            opts[:sprite] = true
        else
            warn("Unknown option: #{ARGV[i]}")
        end
    else
        arg = ARGV[i] unless arg
    end
    i += 1
end

unless arg
    warn("Input file is not specified")
    exit(1)
end

unless File.file?(arg)
    warn("File not found: #{arg}")
    exit(1)
end

assets = []

if opts[:as_asset]
    assets = [Mikunyan::Asset.file(arg, File.basename(arg, '.*'))]
else
    assets = Mikunyan::AssetBundle.file(arg).assets
end

outdir = opts[:outputdir] || File.basename(arg, '.*')
FileUtils.mkpath(outdir)

assets.each do |asset|
    if opts[:sprite]
        textures = {}

        asset.path_ids.select{|path_id| asset.object_type(path_id) == 'Sprite'}.each do |path_id|
            obj = asset.parse_object(path_id)
            name = obj.m_Name.value
            tex_id = obj.m_RD.texture.m_PathID.value

            unless textures[tex_id]
                tex_obj = asset.parse_object(tex_id)
                textures[tex_id] = Mikunyan::ImageDecoder.decode_object(tex_obj) if tex_obj
            end

            if textures[tex_id]
                x = obj.m_Rect.x.value.to_i
                y = obj.m_Rect.y.value.to_i
                width = obj.m_Rect.width.value.to_i
                height = obj.m_Rect.height.value.to_i

                puts "#{outdir}/#{name}.png (#{width} x #{height})"
                textures[tex_id].crop(x, textures[tex_id].height - height - y, width, height).save("#{outdir}/#{name}.png")
            end
        end
    else
        asset.path_ids.select{|path_id| asset.object_type(path_id) == 'Texture2D'}.each do |path_id|
            obj = asset.parse_object(path_id)
            name = obj.m_Name.value
            image = Mikunyan::ImageDecoder.decode_object(obj)
            puts "#{outdir}/#{name}.png (#{image.width} x #{image.height})"
            image.save("#{outdir}/#{name}.png") if image
        end
    end
end
