# TODO add original licence to fonts

class FigletFont
  def initialize(font_file_path)
    lines = File.new(font_file_path).readlines
    # parse first line
    first = lines[0]
    raise 'Wrong file format identifier' if first[0..4] != 'flf2a'
    @space_char = first[5]
    first_numbers = first[6..-1].split(" ")
    @char_height, @char_height_desc, @max_char_width, _, @comment_lines, _ = first_numbers.collect {|i| i.to_i}

    lines = lines.drop(1+@comment_lines)
    
    @letters = {}
    
    (32..126).each do |i|
      letter = lines.take(@char_height)
      lines = lines.drop(@char_height)
      letter.collect! { |l| l.rstrip[0..-2]} # remove last char from each line
      letter[-1] = letter[-1][0..-2] # also remove last char from last line
      letter.collect! { |l| l.gsub(@space_char, " ")} # change space char to space
      @letters[i] = letter
    end
  end
  
  # returns an array of strings for the given char.
  # if center_width is given, the char will be centered to this width
  def letter(char, center_width=nil)
    result = @letters[char.ord]
    unless center_width.nil? then
      pad_total = center_width - result[0].length
      pad_left = pad_total / 2
      pad_right = pad_total / 2
      pad_right += 1 if pad_total.odd?
      # add padding left and right
      result.collect! { |l| " "*pad_left + l + " "*pad_right}
    end
    return result
  end
  
  require_relative "color"
  
  def print_letter_in_box(char, width, color=:white)
    lines = self.letter(char, width)
    puts " " + "-" * width
    lines.each do |l|
      puts "|" + l.colorize(color) + "|"
    end
    puts " " + "-" * width
  end
end