require 'test/unit'
require 'action_mailer'
require 'action_mailer/ar_sendmail'
require 'rubygems'
require 'test/zentest_assertions'

class TestARSendmail < Test::Unit::TestCase

  def setup
    ActionMailer::Base.server_settings.clear
    Email.id = 0
    Email.records.clear
    Net::SMTP.deliveries.clear
    Net::SMTP.on_send_message # reset

    @sm = ActionMailer::ARSendmail.new

    @include_c_e = ! $".grep(/config\/environment.rb/).empty?
    $" << 'config/environment.rb' unless @include_c_e
  end

  def teardown
    $".delete 'config/environment.rb' unless @include_c_e
  end

  def test_class_create_migration
    out, = util_capture do
      ActionMailer::ARSendmail.create_migration 'Email'
    end

    expected = <<-EOF
class AddEmail < ActiveRecord::Migration
  def self.up
    create_table :email do |t|
      t.column :from, :string
      t.column :to, :string
      t.column :last_send_attempt, :integer, :default => 0
      t.column :mail, :text
    end
  end

  def self.down
    drop_table :email
  end
end
    EOF

    assert_equal expected, out.string
  end

  def test_class_create_migration_table_name
    out, = util_capture do
      ActionMailer::ARSendmail.create_migration 'Mail'
    end

    expected = <<-EOF
class AddMail < ActiveRecord::Migration
  def self.up
    create_table :mail do |t|
      t.column :from, :string
      t.column :to, :string
      t.column :last_send_attempt, :integer, :default => 0
      t.column :mail, :text
    end
  end

  def self.down
    drop_table :email
  end
end
    EOF

    assert_equal expected, out.string
  end

  def test_class_create_model
    out, = util_capture do
      ActionMailer::ARSendmail.create_model 'Email'
    end

    expected = <<-EOF
class Email < ActiveRecord::Base
end
    EOF

    assert_equal expected, out.string
  end

  def test_class_create_model_table_name
    out, = util_capture do
      ActionMailer::ARSendmail.create_model 'Mail'
    end

    expected = <<-EOF
class Mail < ActiveRecord::Base
end
    EOF

    assert_equal expected, out.string
  end

  def test_class_mailq
    Email.create :from => nobody, :to => 'recip@h1.example.com',
                 :mail => 'body0'
    Email.create :from => nobody, :to => 'recip@h1.example.com',
                 :mail => 'body1'
    last = Email.create :from => nobody, :to => 'recip@h2.example.com',
                        :mail => 'body2'

    last.last_send_attempt = Time.parse 'Thu Aug 10 11:40:05'

    out, err = util_capture do
      ActionMailer::ARSendmail.mailq
    end

    expected = <<-EOF
-Queue ID- --Size-- ----Arrival Time---- -Sender/Recipient-------
         1        5 Thu Aug 10 11:19:49  nobody@example.com
                                         recip@h1.example.com

         2        5 Thu Aug 10 11:19:50  nobody@example.com
                                         recip@h1.example.com

         3        5 Thu Aug 10 11:19:51  nobody@example.com
Last send attempt: Thu Aug 10 11:40:05 -0700 2006
                                         recip@h2.example.com

-- 0 Kbytes in 3 Requests.
    EOF

    assert_equal expected, out.string
  end

  def test_class_mailq_empty
    out, err = util_capture do
      ActionMailer::ARSendmail.mailq
    end

    assert_equal "Mail queue is empty\n", out.string
  end

  def test_class_new
    assert_equal 60, @sm.delay
    assert_equal Email, @sm.email_class
    assert_equal nil, @sm.once
    assert_equal nil, @sm.verbose
    assert_equal nil, @sm.batch_size

    @sm = ActionMailer::ARSendmail.new :Delay => 75, :Verbose => true,
                                       :TableName => 'Object', :Once => true,
                                       :BatchSize => 1000

    assert_equal 75, @sm.delay
    assert_equal Object, @sm.email_class
    assert_equal true, @sm.once
    assert_equal true, @sm.verbose
    assert_equal 1000, @sm.batch_size
  end

  def test_class_parse_args_batch_size
    options = ActionMailer::ARSendmail.process_args %w[-b 500]

    assert_equal 500, options[:BatchSize]

    options = ActionMailer::ARSendmail.process_args %w[--batch-size 500]

    assert_equal 500, options[:BatchSize]
  end

  def test_class_parse_args_daemon
    argv = %w[-d]
    
    options = ActionMailer::ARSendmail.process_args argv

    assert_equal true, options[:Daemon]

    argv = %w[--daemon]
    
    options = ActionMailer::ARSendmail.process_args argv

    assert_equal true, options[:Daemon]
  end

  def test_class_parse_args_delay
    argv = %w[--delay 75]
    
    options = ActionMailer::ARSendmail.process_args argv

    assert_equal 75, options[:Delay]
  end

  def test_class_parse_args_mailq
    options = ActionMailer::ARSendmail.process_args []
    deny_includes options, :MailQ

    argv = %w[--mailq]
    
    options = ActionMailer::ARSendmail.process_args argv

    assert_equal true, options[:MailQ]
  end

  def test_class_parse_args_migration
    options = ActionMailer::ARSendmail.process_args []
    deny_includes options, :Migrate

    argv = %w[--create-migration]
    
    options = ActionMailer::ARSendmail.process_args argv

    assert_equal true, options[:Migrate]
  end

  def test_class_parse_args_model
    options = ActionMailer::ARSendmail.process_args []
    deny_includes options, :Model

    argv = %w[--create-model]
    
    options = ActionMailer::ARSendmail.process_args argv

    assert_equal true, options[:Model]
  end

  def test_class_parse_args_no_config_environment
    $".delete 'config/environment.rb'

    assert_raise SystemExit do
      out, err = util_capture do
        ActionMailer::ARSendmail.process_args []
      end
    end

  ensure
    $" << 'config/environment.rb' if @include_c_e
  end

  def test_class_parse_args_no_config_environment_migrate
    $".delete 'config/environment.rb'

    out, err = util_capture do
      ActionMailer::ARSendmail.process_args %w[--create-migration]
    end

    assert true # count

  ensure
    $" << 'config/environment.rb' if @include_c_e
  end

  def test_class_parse_args_no_config_environment_model
    $".delete 'config/environment.rb'

    out, err = util_capture do
      ActionMailer::ARSendmail.process_args %w[--create-model]
    end

    assert true # count

  rescue SystemExit
    flunk 'Should not exit'

  ensure
    $" << 'config/environment.rb' if @include_c_e
  end

  def test_class_parse_args_once
    argv = %w[-o]
    
    options = ActionMailer::ARSendmail.process_args argv

    assert_equal true, options[:Once]

    argv = %w[--once]
    
    options = ActionMailer::ARSendmail.process_args argv

    assert_equal true, options[:Once]
  end

  def test_class_parse_args_table_name
    argv = %w[-t Email]
    
    options = ActionMailer::ARSendmail.process_args argv

    assert_equal 'Email', options[:TableName]

    argv = %w[--table-name=Email]
    
    options = ActionMailer::ARSendmail.process_args argv

    assert_equal 'Email', options[:TableName]
  end

  def test_deliver
    email = Email.create :mail => 'body', :to => 'to', :from => 'from'

    @sm.deliver [email]

    assert_equal 1, Net::SMTP.deliveries.length
    assert_equal ['body', 'to', 'from'], Net::SMTP.deliveries.first
    assert_equal 0, Email.records.length
  end

  def test_deliver_500
    Net::SMTP.on_send_message do
      raise Net::SMTPServerBusy
    end

    now = Time.now.to_i

    email = Email.create :mail => 'body', :to => 'to', :from => 'from'

    @sm.deliver [email]

    assert_equal 0, Net::SMTP.deliveries.length
    assert_equal 1, Email.records.length
    assert_operator now, :<=, Email.records.first.last_send_attempt
  end

  def test_log
    @sm = ActionMailer::ARSendmail.new :Verbose => true

    out, err = util_capture do
      @sm.log 'hi'
    end

    assert_equal "hi\n", err.string
  end

  def test_find_emails
    emails = [
      { :mail => 'body0', :to => 'recip@h1.example.com', :from => nobody },
      { :mail => 'body1', :to => 'recip@h1.example.com', :from => nobody },
      { :mail => 'body2', :to => 'recip@h2.example.com', :from => nobody },
    ]

    emails.each do |email| Email.create email end

    tried = Email.create :mail => 'body3', :to => 'recip@h3.example.com',
                         :from => nobody

    tried.last_send_attempt = Time.now.to_i - 258

    found_emails = @sm.find_emails

    expected = [
      Email.new(nobody, 'recip@h1.example.com', 'body0'),
      Email.new(nobody, 'recip@h1.example.com', 'body1'),
      Email.new(nobody, 'recip@h2.example.com', 'body2'),
    ]

    assert_equal expected, found_emails
  end

  def test_server_settings
    ActionMailer::Base.server_settings[:address] = 'localhost'

    assert_equal 'localhost', @sm.server_settings[:address]
  end

  def nobody
    'nobody@example.com'
  end

end