require 'robot'

class RubberDuck
include Robot
  
  
  def tick events
    @myevents = events
    #puts "at #{time}: gun : #{gun_heading}, radar: #{radar_heading}, diff: #{gun_heading-radar_heading}"
    if time == 0
      @arc = 0
      @last_arc = 60
      @last_action = :widen
      turn_radar 30
      @last_distance = 1000
      @initial_heading = calc_initial_heading(x,y,battlefield_width,battlefield_height)
      @circle_mode = false
    end
    
    accelerate 1 if velocity < 8
    
    
    if @circle_mode
      turn 1.5
    else
      turn @initial_heading-heading
      @circle_mode = true if @initial_heading == heading
    end
    
    case @last_distance
      when 0..100 : fire 3
      when 101..300 : fire 1
      else fire 0.1
    end
    
    if contact
      @last_distance = @myevents['robot_scanned'][0][0]
      #puts "got last dist of #{@last_distance}"
      narrow if @last_arc.abs >= 4
    else
      if @last_action == :resweep && @last_arc.abs < 30
        widen 
      else
        resweep
      end
    end
  end
  #double the size of the arc, try to keep it centered on the current centerpoint.
  def widen
      raise "last arc out of wack" if @last_arc.abs > 60
      arc = -2 * @last_arc
      #arc = 60 if arc > 60
      #arc = -60 if arc < -60
    #puts "widening:  last arc was #{@last_arc} new arc is #{arc}"
    turn_gun  0.5 * arc
    turn_radar 0.75 * arc
    @last_arc = arc
    @last_action = :widen
  end
  
  # cut the arc in half and search the half our radar is already on one edge of
  def narrow
    arc = @last_arc / -2
    #puts "narrowing:  last arc was #{@last_arc} new arc is #{arc}"
        
    #some useful debugging info
    turn_gun_amount = -0.5 *arc
    turn_radar_amount = 1.5*arc
    
    new_radar_heading = turn_gun_amount + turn_radar_amount + radar_heading
    #puts "radar will be sweeping from #{radar_heading} to #{new_radar_heading}"
    #puts "arc and radar headings diff don't match!" if new_radar_heading-radar_heading != arc
    
    turn_gun turn_gun_amount
    turn_radar turn_radar_amount
    @last_arc = arc
    @last_action = :narrow
  end
  
  #repeat the last sweep parameters
  def resweep
  raise "last arc out of wack" if @last_arc.abs > 60
    #puts "resweeping:  last arc was #{@last_arc}"
    turn_gun @last_arc
    @last_action = :resweep
  end
  
  def contact
    !@myevents['robot_scanned'].empty?
  end
  
  def calc_initial_heading(x,y,w,h)
    if x > w/2
      if y > h/2 then 90 else 180 end
    else
      if y > h/2 then 0 else 270 end
    end
  end
    
end
