#!/usr/bin/env ruby

require 'term/ansicolor'

class String
  include Term::ANSIColor
end

def print_color(c)
  color = Term::ANSIColor::Attribute[c]
  text = [
    Term::ANSIColor::Attribute.nearest_rgb_color('#000'),
    Term::ANSIColor::Attribute.nearest_rgb_color('#fff'),
  ].max_by { |t| t.distance_to(color) }
  print ("%3u #{color.rgb.html} " % c).on_color(color.name).color(text.name)
end

if Term::ANSIColor.true_coloring = ENV['COLORTERM'] =~ /\A(truecolor|24bit)\z/

  puts "True colors".bold, ""
  step = 36
  (0..255).step(step) do |g|
    (0..255).step(step) do |r|
      (0..255).step(step) do |b|
        print Term::ANSIColor.on_color(Term::ANSIColor::RGBTriple.new(r, g, b)) { ' ' }
      end
      print ' '
    end
    puts
  end

  puts
  (0..255).step(4) do |g|
    print Term::ANSIColor.on_color(Term::ANSIColor::RGBTriple.new(g, g, g)) { ' ' }
  end
  puts
  puts

end

Term::ANSIColor.true_coloring = false

puts "256 colors".bold, ""
for c in 0..3
  print_color c
end
puts

for c in 4..7
  print_color c
end
puts
puts

for c in 8..11
  print_color c
end
puts

for c in 12..15
  print_color c
end

for c in 16..231
  (c - 16) % 6 == 0 and puts
  (c - 16) % 36 == 0 and puts
  print_color c
end
puts

for c in 232..255
  (c - 16) % 6 == 0 and puts
  print_color c
end
puts
