class Agenda::InstitutionEventsController < AgendaController
  respond_to :html, :js
  before_filter :init_search
  hide_action :init_search

  def index
    @start_at = Date.parse(params[:start_at]) rescue Date.current
    @events = InstitutionEvent.includes(:institution).active.search({start_at_gteq: @start_at, start_at_lt: @start_at + 1.day}).result
  end

  def list
    conditions = params[:q] ? params[:q] : {start_at_gteq: Date.current, start_at_lt: Date.current + 1.day}
    @events = InstitutionEvent.includes(:institution).active.order(:start_at).search(conditions).result
    @events = @events.group_by{|event| event.start_at.to_date}
  end

  def week
    @start_at = Date.parse(params[:start_at]) rescue Date.current
    @end_at = @start_at + 4.days
    @events = InstitutionEvent.includes(:institution).active.order(:start_at).search({start_at_gteq: @start_at, start_at_lt: @end_at + 1.day}).result
    @events = @events.group_by{|event| event.start_at.to_date}
  end

  def month
    @start_at = Date.parse(params[:start_at]) rescue Date.current
    @events = InstitutionEvent.includes(:institution).active.order(:start_at).search({start_at_gteq: @start_at.beginning_of_month, start_at_lt: @start_at.end_of_month + 1.day}).result
    @events = @events.group_by{|event| event.start_at.to_date}
  end

  def confirm
    if user_signed_in?
      @institution_event = InstitutionEvent.find(params[:id])
      participant = InstitutionEventParticipant.where(user_id: current_user.id, institution_event_id: @institution_event.id).first_or_initialize
      if participant.new_record?
        participant.save
        @status = 'added'
      else
        participant.destroy
        @status = 'removed'
      end
    else
      @redirect_to_login = true
    end
  end

  def subscribe
    if user_signed_in?
      @institution_event = InstitutionEvent.find(params[:id])
      subscriber = InstitutionSubscriber.where(user_id: current_user.id, institution_id: @institution_event.institution_id).first_or_initialize
      if subscriber.new_record?
        subscriber.save
        @status = 'added'
      else
        subscriber.destroy
        @status = 'removed'
      end
    else
      @redirect_to_login = true
    end
  end

  private
    def init_search
      @q = InstitutionEvent.search(params[:q])
    end

    def institution_event
      @institution_event ||= params[:id] ? InstitutionEvent.find(params[:id]) : InstitutionEvent.new
    end
    helper_method :institution_event
end
