class MessagesController < ApplicationController
  layout :admin_or_application_layout

  before_filter :permision_required

  def send_message
    RegisteredUser.__rails_cannot_find_descendants_fix
    
    receipient = RegisteredUser.find(params[:to_user])
    if Message.new(current_user, receipient, params[:message_body]).deliver!
      flash[:notice] = "Message sent to %s" % receipient.name
    end
    redirect_to profile_url(receipient)
  end
  
  def new_topic_users
    @topic        = Topic.find(params[:id])
    @from         = current_user.email ? current_user.email_address_with_name : Settings.admin_email
    @title        = "Send to users in topic: '#{@topic.title}'"
    @subject      = "[%s] %s" % [Settings.email_subject_label, @topic.title]
    @user_list    = @topic.uniq_reading_participants.collect(&:email_address_with_name)
    @message_body = "Dear {{user_name}}\n\n\nFollow along at:\n#{topic_url(@topic)}"
    set_default_breadcrumb
    @breadcrumb_trail << ['Topics', url_for(:controller => 'topics', :action => 'list')]
    @breadcrumb_trail << @topic.title << "Message users"
  end
  
  def send_topic_users
    @user_list       = Topic.find(params[:id]).uniq_reading_participants
    @message_subject = params[:message_subject]
    @message_body    = params[:message_body]
    if request.post?
      if UserNotifier.gereral_message_many_users(@user_list, @message_subject, @message_body)
        flash[:notice] = "Message sent to %i users" % @user_list.length
        redirect_to :controller => 'topics', :action => 'list'
      end
    else
      render :action => 'new_topic_users'
    end
  end
  
 private
  
  def action_requires_permission?
    action_name != 'send_message'
  end
  
end
