module Irc

  # wrapped TCPSocket for communication with the server.
  # emulates a subset of TCPSocket functionality
  class IrcSocket
    # server:: server to connect to
    # port::   IRCd port
    # host::   optional local host to bind to (ruby 1.7+ required)
    # create a new IrcSocket
    def initialize(server, port, host)
      @server = server.dup
      @host = host
      @port = port.to_i
    end
    
    # open a TCP connection to the server
    def connect
      if(@host)
        begin
          @sock=TCPSocket.new(@server, @port, @host)
        rescue ArgumentError => e
          puts "Your version of ruby does not support binding to a specific"
          puts "local address, please upgrade if you wish to use HOST = foo"
          puts "(this option has been disabled in order to continue)"
          @sock=TCPSocket.new(@server, @port)
        end
      else
        @sock=TCPSocket.new(@server, @port)
      end 
    end
    
    # used to send lines to the remote IRCd
    # message: IRC message to send
    def puts(message)
      #debug "SEND: #{message.inspect}"
      @sock.send(message + "\n",0)
    end

    # get the next line from the server (blocks)
    def gets
      reply = @sock.gets
      if(reply)
        reply.strip!
      end
      #debug "RECV: #{reply.inspect}"
      reply
    end

    # flush the TCPSocket
    def flush
      @sock.flush
    end

    # Wraps Kernel.select on the socket
    def select(timeout)
      Kernel.select([@sock], nil, nil, timeout)
    end

    # shutdown the connection to the server
    def shutdown(how=2)
      @sock.shutdown(how)
    end
  end

end
