# Searching ants. 
#
# An evolution of the homing ants.
# These ants go where the pheromone level is lowest when searching for food

DIRECTIONS = [:north, :east, :south, :west]

module Ant
  class Ant
    attr_accessor :home_x, :home_y

    # FIXME: Is there a concise more general solution for this problem.
    # Given a ring of states and a start and end state, is the shortest way left or right?
    def go(direction)
      return GO if self.direction == direction
      if DIRECTIONS[DIRECTIONS.index(self.direction) - 1] == direction
        TURN_LEFT
      else
        TURN_RIGHT
      end
    end
  end
end

INFINITY = 1.0 / 0.0

def calculate_action(client, ant)
  if ant.cell.home == client.id
    ant.home_x = ant.x
    ant.home_y = ant.y
  end
  if ant.has_food and (ant.cell.home == client.id) # Drop food if we are at home
    DROP_FOOD
  elsif ant.has_food 
    if ant.x < ant.home_x
      ant.go(:east)
    elsif ant.x > ant.home_x
      ant.go(:west)
    elsif ant.y < ant.home_y
      ant.go(:south)
    elsif ant.y > ant.home_y
      ant.go(:north)
    end
  elsif (ant.cell.food > 0) and !ant.has_food and (ant.cell.home != client.id) # Take food if there is food and we are not at home
    TAKE_FOOD
  else # Go where the phermone level is lowest
    pheromone_concentration = DIRECTIONS.map {|d| 
      cell = ant.send("cell_#{d}")
      cell ? cell.friend_pheromone : INFINITY }
    ant.go(DIRECTIONS.min { |d1, d2| pheromone_concentration[DIRECTIONS.index(d1)] <=> pheromone_concentration[DIRECTIONS.index(d2)] })
  end
end