require 'client/chat'

class ChatObserver

  include IGSCP

  def initialize
        #    $igsClient.add_listener(IGSProtocol::TELL){ |code,line| rec_tell(line) }
        #    $igsClient.add_listener(IGSProtocol::YELL){ |code,line| rec_yell(line) }
    @windows= {}
    $notify_list = []
  end

  # 24 *windblow*:  thanks for the game. see you
  #
  def rec_tell(line)

    line =~ /^\*(\S+)\*: (.*)/
	if $1 == 'SYSTEM'
       $revobs.receive($2)
	   return
    end
    if  IGSCP.is_command($2) # treated in gamesobserver
    else
      if @windows[$1].nil?
        if Defaults::DEFS['auto_start_Chat']
          @windows[$1]= Chat.new($1)
          playsound('RingIn.wav')
        else
          return
        end
      end
      @windows[$1].raise if Defaults::DEFS['auto_raise_Chat']
      @windows[$1].rec_message($2)
    end
  end

  def rec_yell(line)
    line =~ /^(\d+):(.*)/
    return if  @windows[$1].nil?
    @windows[$1].rec_message($2)
  end

  def new_chat (player,title=nil)
    @windows[player]= Chat.new(player,title) if @windows[player].nil?
  end


  def delete (player)
    @windows[player]= nil
  end

  def close_all
    return if @windows.nil?
    @windows.each_value { |win| win.close unless win.nil?}
    @windows= nil
  end
  def message(player,msg)
    if @windows[player]
      @windows[player].rec_message(msg,'info')
    end
  end

  def rec_shout(line)
    if line =~ /\{(\S+) \[(\S+) *\] has connected/
        if $notify_list.include?($1)
          new_chat($1,line)
          $notify_list.delete($1)
        end

    elsif line =~ /\{(\S+) has disconnected\}/
      message($1,line)
    end

  end

  def notify(player)
    $notify_list.push(player) unless  $notify_list.include?(player)
  end


end
