require 'socket'
require 'mysql'

class RubyBot
  def initialize(hostname, port, username, password)
    @host = hostname
    @port = port
    @username = username
    @password = password
    @con = Mysql.new('localhost','root','purple4','stdw_market',nil,nil,Mysql::CLIENT_MULTI_STATEMENTS)
    @con.query_with_result=false
    
    @command_hash = { 
      "query" => lambda { 
        |user, args| 
        
        result = String.new("")
        no_more_results=false
        curr_row_count=0

        @con.query(args)

        until no_more_results
          begin
            rs = @con.use_result()
          rescue Mysql::Error => e
            no_more_results = true
          end

          if no_more_results == false
            colcount = rs.num_fields()
            rowcount = rs.num_rows()
            rs.each do |row|
              curr_row_count +=1
              rs.fetch_fields.each_with_index do |col,i|
                if ( i == colcount ) 
                  result.concat(row[i])
                elsif
                  result.concat(row[i] + "|")
                end
              end

              if ( curr_row_count != rowcount )
                result.concat("~")
              end
            end
            rs.free()
            @con.next_result()
          end
        end

        @client.puts "@pemit #{user}=#{result}"
      },
      "create_stored_procedure" => lambda {
        |user, args|
        @post_args = args
        @post_args = @post_args.gsub("^","\n\n")
        @con.query(@post_args)

        if ( @sql_bot.has_error ) 
          @client.puts "@pemit #{user}=#{@sql_bot.get_error_string()}"
        end
      },
      "version" => lambda {
        |user, args|
        @client.puts "@pemit #{user}=#{@sql_bot.version()}"
      },
      "quit" => lambda {
        |user, args|
        @con.close()
        @con = nil
        @client.close
        @client = nil
        exit()
      },
      "restart" => lambda {
        |user, args|
        @con.close()
        @con = nil
        @client.close
        @client = nil
        system("ruby bot.rb &")
        exit()
      }
    }
  end

  def connect()
    @client = TCPSocket.open("#{@host}", "#{@port}")
    @client.puts "connect #{@username} #{@password}"
  end

  def listen_to_game()
    while line = @client.gets
      if ( line =~ /quit/ )
        closeSocket()
      end
      if ( line =~ /<BOT:(.*):(#\d+)>(.*)/ )
        if ( @command_hash.has_key?("#{$1}") )
          @command_hash["#{$1}"].call($2, $3)
        else
          @client.puts "@pemit {#$2}=#-1 INVALID COMMAND '#{$1}'"
        end
      end
    end
  end

  def closeSocket()
    @sql_bot = nil
    @client.close
    @client = nil
    exit()
  end

  def speak(message)
    @client.puts "say #{message}"
  end

  def getConnectInfo()
    puts "Host : #{@host}"
    puts "Port : #{@port}"
    puts "User : #{@username}"
    puts "Pass : #{@password}"
  end
end

bot = RubyBot.new('localhost',4201,'test','blah')

#puts "bot id is #{bot.object_id}"

bot.connect()
bot.listen_to_game()

