module Perdu
  class InMemoryStore
    def initialize
      @ids = {}
      @store = {}
      @id_field = :id
    end

    def create(type, attributes)
      id = generate_id(type)
      attributes[@id_field] = id
      store_for(type)[index_for(id)] = attributes
      attributes
    end

    def find(type, fields)
      if fields.has_key?(@id_field)
        store_for(type)[index_for(fields[@id_field])]
      else
        store_for(type).select do |hash|
          fields.all? { |a, v| hash[a] == v}
        end.first
      end
    end

    def all(type)
      store_for(type)
    end

    private

    attr_reader :store
    attr_reader :ids

    def store_for(type)
      store[type] ||= []
    end

    def index_for(id)
      id - 1
    end

    def generate_id(type)
      ids[type] ||= 0
      ids[type] += 1
      ids[type]
    end
  end
end
