# vim:ts=4:autoindent

require 'Log'

class Email
    def initialize(dd)
        @dd = dd
        @dd.on_event( self, :type => :email ){ |ev| do_email(ev) }
    end

    def do_email(ev)
        acct = ev[:acct]
        u = ev[:user]

        if ev[:to].nil?
            # Reading email.
            email = @dd.accts[acct][:emails].shift if ( !@dd.accts[acct].nil? && !@dd.accts[acct][:emails].nil? )
            if email
                u.privmsg "~\r"
                u.privmsg "~==> From: ##{"%03d" % email[0]} #{email[1]}\r"
                u.privmsg "~#{email[2]}\r"
                u.privmsg "~==> Date Sent: #{email[3].strftime("%m/%d %I:%M %p")}\r"
                u.privmsg "~\r"
            else
                u.privmsg "~--> No Email\r"
            end
            @dd.accts[acct] ||= {}
            @dd.accts[acct][:last_read_email] = Time.now
        else
            to = ev[:to]
            fromhandle = u.handle

            if ev[:message].length == 0
                # Checking last read email time.
                lastread = @dd.accts[to][:last_read_email] if ( !@dd.accts[to].nil? && !@dd.accts[to][:last_read_email].nil? )
                if lastread
                    u.privmsg "~--> #{lastread.strftime("%m/%d %I:%M %p")}\r"
                else
                    u.privmsg "~--> 00/00 00:00 PM\r"
                end
            else
                # Sending email.
                @dd.accts[to] ||= {}
                @dd.accts[to][:emails] ||= []
                if @dd.accts[to][:emails].length > 15
                    @dd.write( "/P#{line}~--> Email Box Full\r" )
                else
                    @dd.accts[to][:emails] << [ acct, fromhandle, ev[:message], Time.now ]
                end
            end
        end
    end
end