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

class RegistrationFiltersControllerTest < Test::Rails::ControllerTestCase
  fixtures :registration_filter_items, :users

  def setup
    super
    ApplicationPolicy.stubs(:guests_allowed?).returns(true)
    ApplicationPolicy.stubs(:participation_enabled?).returns(true)
    login_as :laura
  end
  
  def test_index
    get :index, :topic_id => 1
    assert_response :success 
    assert_assigned :whitelist_filters
    assert_assigned :mask_filters
  end  
  
  def test_index_only_admin_can_access
    assert_requires_login(:quentin) { get :index, :topic_id => 1}
  end
  
  def test_delete_removes_item
    assert_difference(RegistrationFilterItem, :count, nil, -1){ get :delete, :id => 1, :topic_id => 1}
  end
  
  def test_delete_sets_flash
    get :delete, :id => 1, :topic_id => 1
    assert flash[:notice]
  end
  
  def test_delete_redirects
    get :delete, :id => 1, :topic_id => 1
    assert_response :redirect
    assert_redirected_to :action => 'index'
  end
  
  def test_create_mask
    assert_difference(MaskFilterItem, :count) { create_mask }
  end
  
  def test_create_whitelist
    assert_difference(WhitelistFilterItem, :count) { create_whitelist }
  end
  
  def test_create_whitelist_invalid
    assert_no_difference(WhitelistFilterItem, :count) { create_whitelist('not an email') }
  end

  def test_create_whitelist_invalid_sets_flash
    create_whitelist('not an email')
    assert flash[:alert]
  end
  
  [:create_mask, :create_whitelist].each do |action|
    define_method("test_#{action}_redirects") do
      send(action)
      assert_response :redirect
      assert_redirected_to :action => 'index'
    end

    define_method("test_#{action}_sets_flash") do
      send(action)
      assert_nil flash[:alert]
      assert     flash[:notice]
    end
  end
  
  def test_upload_whitelist
    assert_difference(WhitelistFilterItem, :count, nil, 3) do
      upload_whitelist
    end
  end
  
  def test_upload_whitelist_sets_notice
    WhitelistFilterItem.stubs(:add_in_bulk).returns({:new_items_count => 1, :failed_saves => []})
    upload_whitelist
    assert flash[:notice]
  end
  
  def test_upload_whitelist_sets_flash
    WhitelistFilterItem.stubs(:add_in_bulk).returns({
      :new_items_count => 0, 
      :failed_saves => [stub(
        :value => 'v', 
        :errors => stub(:full_messages => 'cat'))
        ]
      })
    upload_whitelist
    assert flash[:alert]
  end
  
  def create_mask()
    create_filter(:create_mask, '*@yahoo.com')
  end
  
  def create_whitelist(value = 'bob@yahoo.com')
    create_filter(:create_whitelist, value)
  end
  
  def create_filter(action, value)
    post action, :value => value, :topic_id => 1
  end
  
  def upload_whitelist
    post :upload_whitelist, :file => fixture_file_upload('files/whitelist_emails.txt'), :topic_id => 1
  end
end
