

class GoPlayer < GoObserver

  def initialize( header,title=nil)
    super( header,title)
    @kind_of_talk= 'say'
    @my_color=(@white == $user ? 'W' : 'B')
    @opponent=(@white == $user ? @black : @white)
    @opponent_lost_connection=false
    enable_menus

    @top.help_add('command','label'=>'Playing a game','command'=>proc { TkHtml.new("file://#{$current_path}/../help/gamewindow.html#playing") })

  end

  def quit

    if @game_adjourned or @game_completed 
      $gamesobserver.delete(@number) unless $gamesobserver.nil?
      close
    else
      #  error, info, question, or warning
      # 'AbortRetryIgnore', 'OK', 'OKCancel', 'RetryCancel', 'YesNo' or 'YesNoCancel'.
      Misc.warning( "You must adjourn the game\nbefore closing the window.")
    end
  end

  def open_win
    super

    @top.title(TkDefaults::GUI['GoPlayer.top']['title']+$user)
    if $set_komi
       $igsClient.send("komi #$set_komi")
       $set_komi=nil
    end
    if $set_free
       $igsClient.send("free")
       $set_free=nil
    end
    @cmdline.focus
  end

    def open_cmd 
      @cmd2= VTexturedPane.new(@f1,Defaults::DEFS['CommonBackground'],10,5,1,6).pack('side'=>'right','fill'=> 'both','expand'=>'yes')

      opts=TkDefaults::GUI['GoPlayer.button.free'].update( {'command'=> proc {send_free}})
      TkButton.new(@cmd2,opts).pack('padx'=>5,'pady'=>5)


      make_entry(@cmd2,'Handicap'){ | handi| send_handi(handi)}.pack('padx'=>5,'pady'=>5)
      make_entry(@cmd2,'Add time'){ | time| send_addtime(time)}

      opts=TkDefaults::GUI['GoPlayer.button.undo'].update( {'command'=> proc {send_undo}})
      TkButton.new(@cmd2,opts).pack('padx'=>5,'pady'=>5)

      opts=TkDefaults::GUI['GoPlayer.button.pass'].update( {'command'=> proc {send_pass}})
      TkButton.new(@cmd2,opts).pack('padx'=>5,'pady'=>5)

      opts=TkDefaults::GUI['GoPlayer.button.adjourn'].update( {'command'=> proc {send_adjourn}})
      TkButton.new(@cmd2,opts).pack('padx'=>5,'pady'=>5)

      opts=TkDefaults::GUI['GoPlayer.button.done'].update( {'command'=> proc {send_done}})
      TkButton.new(@cmd2,opts).pack('padx'=>5,'pady'=>5)

      opts=TkDefaults::GUI['GoPlayer.button.resign'].update( {'command'=> proc {send_resign}})
      TkButton.new(@cmd2,opts).pack('padx'=>5,'pady'=>5)

    end

def set_root(root)
   super(root)
    @goban.unset_shift_click
     @goban.unset_ctrl_click
end

    def make_entry(parent,name,&action)
      frame = TkFrame.new(parent).pack('padx'=>5,'pady'=>5)
      opts=TkDefaults::GUI['GoPlayer.button.' + name ]
      button= TkButton.new(frame,opts).pack

      fr = TkFrame.new(frame)# .pack('side'=>'left','fill'=>'y','expand'=>'yes')
      var = TkVariable.new
      opts=  TkDefaults::GUI['GoPlayer.entry'].update('textvariable'=> var)
      param =  TkEntry.new(fr,opts).pack('side'=>'left','fill'=>'y','expand'=>'yes')

      opts=  TkDefaults::GUI['GoPlayer.button.ok.' + name ].update(
                                                                   'command'=> proc {action.call(var.value); fr.unpack; button.pack})
      btn= TkButton.new(fr,opts).pack('side'=>'left','fill'=>'x')

      button.configure( {'command'=> proc {button.unpack; fr.pack; param.focus}})
      Tk.update
      frame
    end

    def set_lost_connection(line)
      set_msg(line)
      @opponent_lost_connection=true
    end

    def set_adjourned(line)
      super(line,  @opponent_lost_connection)
      @goban.undrag_stone if @goban
    end

    def set_resigned(line)
      super(line)
      @goban.undrag_stone if @goban
      $chatobserver.new_chat(@opponent)
    end

    def send_message(msg)
      @buf_comments << msg << "\n"
      putline(msg , 'user_cmd')
      if @kind_of_talk== 'say'
        $igsClient.send( "say #{msg}")
      elsif  @kind_of_talk== 'tell'
        $igsClient.send( "tell #@opponent #{msg}") 
      end
    end

    def set_completed(g,line)
      super(g,line)
      @goban.cursor('')
      @goban.undrag_stone if @goban
      $chatobserver.new_chat(@opponent)
    end

    def set_turn(color)
      return if @game_over 
      super(color)
    end

    def ready
      return if @goban.nil? or @top.nil? or @last_move.nil?# or @game_over
      if @player_turn == @my_color 
        @goban.drag_stone(@my_color){ |col,row| send_move(col,row) } 
      else
        @goban.undrag_stone
	#	if  @real_time
	#		myclock= @clocks[@my_color]
	#		 debug "#{@real_time} - #{myclock} = #{@real_time - myclock}" if @real_time  <  myclock  
	#	end
      end
    end

    def rec_message(line,tag)

      putline(line, tag) 
      @buf_comments << line << "\n" unless tag == 'tell' and not line.index(@opponent)
#    if tag == 'tell' and @kind_of_talk == 'say' and line.index(@opponent)
#      @kind_of_talk = @opponent
#        putline("#@opponent use 'tell', setting you to 'tell'", 'info')
#	elsif tag == 'say' and line.index(@opponent) and @kind_of_talk == @opponent
#	      @kind_of_talk = 'say'
#	      putline("#@opponent use 'say' again, setting you to 'say'", 'info')
#    end
    end

    def rec_error(line)
      putline(line , 'error') 

      if line =~ /Illegal move/
        @goban.drag_stone(@my_color){ |col,row| send_move(col,row) } unless  @game_over
      end
    end

    def addtime(msg,name,minutes)

      if name == @white
        @clocks['W'] += minutes * 60
        @w_p_inf.set_clock(@clocks['W'] )
      elsif name == @black
        @clocks['B'] += minutes * 60
        @b_p_inf.set_clock( @clocks['B'])
      else
        debug "player #{name} not found"
        return
      end
      set_msg(msg)
    end

    def game_finished(line)

      @game_over=true
      @goban.undrag_stone
      @w_pris_finish= @w_pris
      @b_pris_finish= @b_pris
      @goban.cursor('pirate')
      @goban.set_click { |col,row| send_remove(col,row) }
      stop_timers
      txt='Click to remove dead stones, press "done" when finished'
      blink(@node_name,txt,8)
      playsound('Trumpet1.wav')
    end

   # Game 322 satanas is removing @ D6
 #satanas (W:O): 24.5 to diabolicum (B:#): 34.0
    def send_remove(col,row)
      return if col.nil? or row.nil?
      return unless @game[col][row]== ?W or @game[col][row]== ?B
    # debug Grid.to_coords(col,row, @size)
      $igsClient.send(Grid.to_coords(col,row, @size)+ " #@number")
    end

    def del_remove
      @goban.del_remove
      @w_p_inf.set_pris(@w_pris_finish)
      @b_p_inf.set_pris(@b_pris_finish)
    end

    def set_removing(line)
      set_msg(line)
      line =~ /.* @ (\S+)$/
      col,row = Move.to_cr($1)
      c,r = Grid.to_int(col,row, @size )
  #debug c
  #debug r
  #      debug @goban.board[c][r]
      #
      color= @goban.board[c][r].color
      pris=@goban.remove(c,r )

      if pris> 0
        p_inf= (color == 'W' ? @b_p_inf : @w_p_inf)
      # debug ("remove #{pris} stones of #{color}")
      p_inf.inc_pris(pris)

    end
    playsound('CashReg.wav')
  end

  def send_handi(handi)
    return if handi.empty?
    putline("command: handicap #{handi}", 'user_cmd')
        $igsClient.send( "handicap #@number #{handi}") unless handi.empty?
      end

      def send_addtime(time)
        return if time.empty?
        putline("command: addtime #{time}", 'user_cmd')
        $igsClient.send( "addtime #@number #{time}") unless time.empty?
      end

      def send_move(col,row)
   # debug "#{col},#{row}"
    @real_time= @clocks [@my_color]

    @goban.cursor('watch')
    $igsClient.send( Grid.to_coords(col,row, @size)+ " #@number #{@real_time}")
      end

      def send_undo
        putline("command: undo", 'user_cmd')
#5 Can only have mulitple UNDOs in a teach game.
#    $igsClient.send("undo #@number")
        $igsClient.send("undo")
      end

      def send_pass
        putline("command: pass", 'user_cmd')
        $igsClient.send("pass #@number")
      end

      def send_done
        putline("command: done", 'user_cmd')
        $igsClient.send("done #@number")
      end

      def send_free
        $igsClient.send("free #@number")
      end

      def send_resign
      #  error, info, question, or warning
      # 'AbortRetryIgnore', 'OK', 'OKCancel', 'RetryCancel', 'YesNo' or 'YesNoCancel'.
    ask= Misc.warning('Are you sure you want to resign the game ?','okcancel')
        playsound('Ohno.wav')
        $igsClient.send("resign #@number") if ask == 'ok'
      end

      def send_adjourn
        set_msg('Requesting an adjournment to your opponent')
        $igsClient.send("adjourn #@number")
      end

      def send_addt(time)
        $igsClient.send("addtime #@number #{time}")
      end

      def decrease_clock(who)

        super(who)

        if who == @my_color
          if @clocks[who] < 60 and @byos[who] > 0
            if not @played_sound
              playsound('alarm.wav')
              @played_sound=true
            end
          else
            @played_sound=false
          end
        end
      end

      def ask_komi(line)
	 #9 satanas wants the komi to be 10.5

	 line =~ /(\S+) wants the komi to be +(\d+\.?\d?)/
	 if $1 != $user
		ask= Misc.ask(line)
		if ask == "ok"
			$igsClient.send("komi #$2")
		end		
	end
	   
      end

      def show_vars;end
      def config_btns;end
    end


