class ScheduleEvent < ActiveRecord::Base
  attr_accessible :is_external, :status, :start_at, :place, :address, :reason, :inputs, :require_entry, :entry_status
  attr_accessible :schedule_event_participants_attributes, :status

  # associations
  belongs_to :schedule
  belongs_to :user
  has_many :schedule_event_participants, dependent: :destroy
  accepts_nested_attributes_for :schedule_event_participants, reject_if: :all_blank, allow_destroy: true

  # validations
  validates_presence_of :schedule_event_participants

  # scopes
  scope :draft, where(status: 'draft')
  scope :approved, where(status: 'approved')
  scope :closed, where(status: 'closed')
  scope :reprogram, where(status: 'reprogram')
  scope :current, lambda { where(start_at: Date.current.beginning_of_day .. Date.current.end_of_day, status: ['approved', 'reprogram']).order(:start_at) }

  # methods
  def participants
    schedule_event_participants.map(&:name).join(', ')
  end

  def owner? current_user
    return true if current_user.id == schedule.owner_id
    false
  end

  def self.for_user current_user, role
    if role == 'applicant'
      where(user_id: current_user.id)
    else
      scoped
    end
  end
end
