require File.dirname(__FILE__) + '/../test_helper'
require 'user_notifier'

class UserNotifierTest < Test::Rails::TestCase
  FIXTURES_PATH = File.dirname(__FILE__) + '/../fixtures'
  CHARSET = "utf-8"

  include ActionMailer::Quoting
  
  fixtures :users, :comments, :settings, :topics

  def setup
    ActionMailer::Base.delivery_method = :test
    ActionMailer::Base.perform_deliveries = true
    ActionMailer::Base.deliveries = []

    @expected = TMail::Mail.new
    @expected.set_content_type "text", "plain", { "charset" => CHARSET }
  end

  def test_signup_email
    response = UserNotifier.deliver_signup_notification(users(:grace))
    assert_equal users(:grace).email, response.to[0]
    assert_equal users(:grace).email_address_with_name, response.header['to'].to_s
  end
  
  def test_reply_notification
    response = UserNotifier::deliver_reply_notification(users(:ernest), comments(:second_reply))
    assert_equal users(:ernest).email, response.to[0]
    assert_match "\/show\/#{comments(:second_reply).topic.id}#comment_#{comments(:second_reply).id}", response.body
  end
  
  def test_password_reminder
    response =UserNotifier.deliver_password_reminder(users(:quentin))
    assert_match users(:quentin).password, response.body
    assert_match Settings.application_url, response.body
  end
  
  def test_pk_gets_bbced
    response = UserNotifier.deliver_signup_notification(users(:grace))
    assert_equal 'pierre.killeen@gmail.com, lee@omara.ca', response.header['bcc'].to_s
  end
  
  def test_deliver_general_message                 # (to, subject, body)
    response = UserNotifier::deliver_general_message(users(:grace), 'foo!', '{{user_name}} womp!')
    assert_match 'Grace', response.body
  end
  
  def test_gereral_message_many_users
    user_list = Participant.find(:all)
    UserNotifier::gereral_message_many_users(user_list, 'subjy', '{{user_name}} body')
    assert_equal user_list.length, ActionMailer::Base.deliveries.length
  end
  
  def test_gereral_message_many_users_sends_from_settings_email
    user_list = Participant.find(:all, :limit => 3)
    UserNotifier::gereral_message_many_users(user_list, 'subjy', '{{user_name}} body')
    assert ActionMailer::Base.deliveries.all?{|m| Settings.admin_email == m.header['from'].to_s }
  end
  
  private
    def read_fixture(action)
      IO.readlines("#{FIXTURES_PATH}/user_notifier/#{action}")
    end

    def encode(subject)
      quoted_printable(subject, CHARSET)
    end
end
