require 'json'
require 'pp'

class FixtureFormatter

  def initialize(fixtures)
    @fixtures = fixtures
    if ENV["DEBUG"]
      puts "Loaded fixtures:"
      pp @fixtures
    end
  end

  def json(path, options={})
    result = nil
    begin
      result = JSON.pretty_generate(get_fixture(path, options))
    rescue
      raise "Fixture '#{path}' is absent"
    end
    options[:spaces] = 4 unless options[:spaces]
    result = shift_to_right(result, options[:spaces])
    result
  end

  def get_fixture(path, options={})
    keys = path.split('/')
    hash = @fixtures
    keys.each do |key|
      hash = hash[key]
      puts "Fixtures: value in nil for key '#{key}'" if hash.nil?
    end
    hash = hash.clone
    hash.merge!(options[:value]) if options[:value]
    hash.delete(options[:without_field]) if options[:without_field]
    hash
  end

  private

  def shift_to_right(text, spaces_count)
    buffer = ''
    first_line = true
    text.each_line do |line|
      if first_line
        first_line = false
        buffer += line
        next
      end
      buffer += (' ' * spaces_count) + line
    end
    buffer
  end
end
