#!/usr/bin/ruby
###############################################################################
# Ants client. 
#
# Synopsis
# ants_client [host [port [type]]]
#
# Connects to an ant server on "host:port" and simulates the ants defined in
# types/"type".rb. 
#
# The loaded ruby file should declare a function 
#  def calculate_action(client, ant)
#  end
# that returns one of the possible ant actions. See API for more information.
###############################################################################
# (c) 2004 Brian Amberg
# This code is licenced under the GPL
###############################################################################
# $Revision$
###############################################################################

require 'socket' # TCP communication
require 'thread' # Multi Threading.
require 'ants'
require 'pp'

# Server specific classes
module AntGame::Client
  include AntGame

  class ClientAnt < Ant
    attr_accessor :id
    attr_accessor :cell, :cell_north, :cell_east, :cell_south, :cell_west

    def initialize(client)
      super()
      @client = client
    end
  end

  class AntClient    
    attr_reader :ants, :socket, :id
    
    def initialize(host, port)
      @ants = {}
      @socket = TCPSocket.new(host, port)
      @on_new_round
    end

    def listen
      begin
        while line = @socket.gets("\n")  
          if /^#{Protocoll::PLAYER_ID} <(.*)>$/ =~ line
            @id = $1.to_i
          elsif /^#{Protocoll::ANT} <(.*)>$/ =~ line            
            info = Marshal.load($1.hex_decode)
            @ants[info.id] ||= ClientAnt.new(self)
            info.update_ant(@ants[info.id])

            action = get_action(@ants[info.id])
            @socket.print "#{Protocoll::ANT} <#{action}>\n"
          end
        end
      ensure
        socket.close
      end
    end
  end

  def on_calculate_action(&block)
    @on_calculate_action = block
  end
  
  private
  def get_action(ant)
    return Action::WAIT unless @on_calculate_action
    @on_calculate_action.call(ant)
  end
end

include AntGame::Client
include AntGame::Actions
host, port = ARGV[0] || 'localhost', ARGV[1] || 11112 
type = ARGV[2] || 'random' # Load random ants by default
client = AntClient.new(host, port)

# Load ant type given on commandline
load "types/#{type}.rb"

client.on_calculate_action do | ant | calculate_action(client, ant) end

client.listen