require "optparse"

require "rubygems"
require "color/rgb/jp"

module Enumerable
  def sum
    self.inject(0.0){|s,e| s + e }
  end
end

class Color::RGB
  def to_a
    [r, g, b]
  end

  def distance(other)
    euclid_distance(self.to_a, other.to_a)
  end

  private

  def euclid_distance(a, b)
    Math.sqrt(a.zip(b).map{|aa,bb| (aa - bb) ** 2 }.sum)
  end
end

def palletize(pallet, color, n = 1)
  pallet.sort_by {|e| color.distance(e.rgb) }[0...n]
end


pallets = [Color::RGB::JP::JISZ8102, Color::RGB::JP::Traditional]
n = 3
ARGV.options do |opt|
  opt.banner = "Usage: palletize [-n] rgb_hex_values..."
  opt.on("-n=N", "output top N candidates", Integer) {|v| n = v }
  opt.parse!
end
if ARGV.empty?
  ARGV.options.parse("-h")
  exit 1
end

ARGV.each do |c|
  rgb = Color::RGB.from_html(c)
  puts "=== %s (%s) ===" % [c, rgb.html]
  puts
  pallets.each do |pallet|
    puts "  [%s]" % pallet.name
    puts
    alts = palletize(pallet, rgb, n)
    alts.each_with_index do |alt, i|
      puts "  %2d: %-20s %s" % [i + 1, alt.name.romaji, alt.rgb.html]
    end
    puts
  end
end
