class Event < ApplicationRecord
  scope :ordered_events, -> { order(:date_time) }
  scope :upcoming_events, -> {where("date_time > ?", Time.now.getlocal)}
  scope :by_user, ->(user_id) {joins(:user_events).where(user_events: {user_id: user_id, attending: true})}

  has_many :user_events, dependent: :destroy
  has_many :users, :through => :user_events
  
  validates :name, uniqueness: {case_sensitive: false}
  validates :location, presence: {allow_blank: true}
  validates :date_time, presence: true
  after_create :creator_rsvp

  attr_reader :date, :time
  attr_accessor :creator_id

  def date_time=(date_time)
    write_attribute(:date_time, date_time.to_datetime.localtime)
  end

  def date
    @date = self.date_time.strftime('%m-%d-%Y')

  end

  def time
    @time = self.date_time.strftime('%I:%M %p')
  end

  private
  def creator_rsvp
    if self.id.present?
      self.user_events.create(event_id: self.id, user_id: self.creator_id, creator: true)
    end
  end
end
