class InstitutionEvent < ActiveRecord::Base
  # accessibles
  attr_accessible :active, :name, :institution_id, :place, :start_at, :end_at, :attend, :description, :notes
  attr_accessible :contact_name, :contact_charge, :contact_phone, :contact_email

  # relations
  belongs_to :institution
  has_many :institution_event_participants, dependent: :destroy

  # validations
  validates :name, :place, :attend, :contact_name, :contact_charge, :contact_phone, :contact_email, length: { maximum: 200 }
  validates :name, :institution_id, :place, :start_at, :end_at, :attend, :description, presence: true

  # scopes
  scope :active, where(active: true)

  # delegates
  delegate :name, :acronym, :highlight_events?, to: :institution, allow_nil: true, prefix: true

  # methods
  def have_contact?
    contact_name? or contact_charge? or contact_phone? or contact_email?
  end

  def hour
    [start_at.try(:strftime, '%H:%M'), end_at.try(:strftime, '%H:%M')].join(' - ')
  end

  def participants_count
    institution_event_participants.count
  end

  def subscribe?(current_user)
    return false unless current_user
    InstitutionSubscriber.where(institution_id: institution_id, user_id: current_user.id).any?
  end

  def participe?(current_user)
    return false unless current_user
    InstitutionEventParticipant.where(institution_event_id: id, user_id: current_user.id).any?
  end
end
