require 'emoji_data'

module Emojistatic
  # Clean up the manifest generated by manifesto to add a static prefix to URIs
  def self.prefix_manifest(manifest, prefix)
    cleaned = manifest.clone
    cleaned.gsub!(
      /^\//,
      "#{prefix}/"
    )
    cleaned.gsub!(
      "Generated by manifesto (http://github.com/johntopley/manifesto)",
      "Generated by manifesto (http://github.com/johntopley/manifesto)\n# Modified by emojistatic (http://github.com/mroth/emojistatic)"
    )
  end

  def self.generate_css_map
    working_map = EmojiData.all.reject { |c| c.doublebyte? } #get rid of doublebyte chars until we figure out how to represent in map (TODO:)
    distance_map = [0] + working_map.each_cons(2).collect {|i| (i[1].unified.hex - i[0].unified.hex) }
    combined_map = working_map.zip(distance_map)

    reduced_map = []
    combined_map.each do |char, distance|
      if distance == 1
        active_range = reduced_map.last
        active_range.finish = char.unified
        active_range.size += 1
      else
        reduced_map << CharRange.new(char.unified)
      end
    end
    reduced_map.join(',')
  end

  private
  class CharRange
    attr_reader :start
    attr_accessor :finish, :size

    def initialize(start)
      @start = start
      @finish = start
      @size = 1
    end

    def to_s
      return "U+#{@start}" if @size == 1
      "U+#{@start}-#{@finish}"
    end
  end
end