class RegistrationFiltersController < ApplicationController
  layout "admin"

  verify :params => "topic_id",
         :redirect_to => { :controller => "topics" }

  before_filter :permision_required, :load_topic
  
  def index
    @title = "Access for '%s'" % @topic.title
    @whitelist_filters = @topic.whitelist_filter_items
    @mask_filters      = @topic.mask_filter_items
    set_default_breadcrumb
    @breadcrumb_trail << ['Topics', url_for(:controller => 'topics', :action => 'list')]
    @breadcrumb_trail << @topic.title << "Access"
  end
  
  def create_mask
    create_using(:mask_filter_items) && return
  end
  
  def create_whitelist
    create_using(:whitelist_filter_items) && return
  end
  
  def delete
    item = @topic.registration_filter_items.find(params[:id])
    if item.destroy
      flash[:notice] = "Successfully removed '#{item.value}'"
    end
    redirect_to :action => 'index', :topic_id => @topic.id
  end
  
  # process uploaded text file
  def upload_whitelist 
    results        = @topic.whitelist_filter_items.add_in_bulk(params[:file])
    flash[:notice] = "Added #{results[:new_items_count]} emails to whitelist"
    flash[:alert]  = results[:failed_saves].collect {|item| "#{item.value} #{item.errors.full_messages}" }.join('<br \>') unless results[:failed_saves].empty?
    redirect_to :action => 'index', :topic_id => @topic.id
  end
  
  def privatize
    @topic.make_private!
    flash[:notice] = "Topic made private"
    redirect_to :action => 'index', :topic_id => @topic.id
  end

  def publicize
    @topic.make_public!
    flash[:notice] = "Topic made public"
    redirect_to :action => 'index', :topic_id => @topic.id
  end
  
 private
  
  def create_using(association)
    item = @topic.send(association).build(:value => params[:value])
    if item.save
      flash[:notice] = "Successfully saved '#{item.value}' filter"
    else
      flash[:alert] = item.errors.full_messages
    end
    redirect_to :action => 'index', :topic_id => @topic.id
  end
 
  def action_requires_permission?
    true
  end
  
  def load_topic
    @topic = Topic.find(params[:topic_id])
  end
  
end
