require 'socket'
require 'pony'
require 'base64'

class EmailBot
  def initialize(host, port, username, password, from_email)
    @host = host
    @port = port
    @user = username
    @pass = password
    @from = from_email
    @email = {}
 
    @command_hash = {
      "to" => lambda {
        |user, args|
        @email["to"] = args.chop
        @client.puts "@pemit #{user}=Preparing to send email to: #{@email['to']}"
      },
      "from" => lambda {
        |user, args|
        @email["from"] = args.chop
        @client.puts "@pemit #{user}=Email being sent from: #{@email['from']}"
      },
      "subject" => lambda {
        |user, args|
        @email["subject"] = args.chop
        @client.puts "@pemit #{user}=Setting email subject line to: #{@email['subject']}"
      },
      "body" => lambda {
        |user, args|
        body = args.gsub!("%r", "<br>")
        @email["body"] = body
        @client.puts "@pemit #{user}=Body set."
      },
      "body-append" => lambda {
        |user, args|
        body = body + args.gsub!("%r", "<br>")
        @email["body"] = body
        @client.puts "@pemit #{user}=Text appended to Body."
      },
      "body-prepend" => lambda {
        |user, args|
        body = args.gsub!("%r", "<br>") + body
        @email["body"] = body
        @client.puts "@pemit #{user}=Text pre-pended to Body."
      },
      "send" => lambda {
        |user, args|

        if @email["to"] == nil
          @client.puts "@pemit #{user}=No 'To' specified"
          break
        end

        if @email["subject"] == nil
          @client.puts "@pemit #{user}=No 'Subject' specified"
          break
        end

        if @email["body"] == nil
          @client.puts "@pemit #{user}=No 'Body' specified"
          break
        end

        if @email["from"] == nil
          @from_new = @from
        else
          @from_new = @email["from"]
        end

        Pony.mail(:to => @email["to"], :from => @from_new, :subject => @email["subject"], :html_body => @email["body"])

        @email.clear
      }
    }

  end

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

  def listen_to_game()
    while line = @client.gets
      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
end

curr_bot = []
count = 0

IO.foreach("emailbot.txt") {
  |block|

  a = {} ; block.split(/,/).map { |i| k,v = i.split(/:/,2); a[k] = v }

  curr_bot[count] = Thread.new {
    bot = EmailBot.new(a["game"], a["port"], a['user'], a['pass'], a['from'].chop)
    bot.connect()
    bot.listen_to_game()
    count += 1
  }  
}

curr_bot.each { |aThread| aThread.join }

