class Campaign < ActiveRecord::Base
  attr_accessible :name, :start_date, :end_date, :cause, :homepage, :short_description, :long_description, :campaign_news
  attr_protected :campaign_moderators

  validates :name, :presence => true, :allow_blank => false
  validates :start_date, :presence => true

  # A Campaign is owned by a Cause
  belongs_to :cause, foreign_key: :cause_id, :inverse_of => :campaigns

  has_many :campaign_moderators, :inverse_of => :campaign
  validates_associated :campaign_moderators

  #implied through-association to make life a bit easier
  has_many :moderators, :through => :campaign_moderators, :source => 'user', :as => User

  # basically forms a semi-blog structure, allowing moderators to post news items about the Campaign
  has_many :campaign_news
  validates_associated :campaign_news

  has_many :images, :class_name => Upload
  validates_associated :images

  # make sure that the default_values method is called after the constructor, this will initialise any
  # default values into the object before the constructor returns.
  after_initialize :default_values

  def self.create_campaign!(current_user, params)
    campaign = Campaign.new()

    params.each { |key, value| campaign.send "#{key}=", value }
    campaign.save!

    CampaignModerator.grant_permission!(current_user, campaign, :owner)

    campaign
  end

  private
  def default_values
    self.start_date ||= Time.now
  end
end
