class EasyActivitiesController < ApplicationController

  include EasyActivitiesHelper
  helper :activities
  before_action :authorize_global
  before_action :find_activity_feed_page_module, :only => [:events_from_activity_feed_module, :show_selected_event_type], :if => Proc.new { !params[:defaults] }

  def show_toolbar
    @events = EasyActivity.last_current_user_events_with_defaults
    @events.sort! {|x,y| y.event_datetime <=> x.event_datetime }
    @events_by_day = @events.group_by {|event| User.current.time_to_date(event_update_datetime(event))}

    respond_to do |format|
      format.js
    end
  end

  def show_selected_event_type
    @activity_feed_page_module.settings ||= {}
    if params[:event_type_id]
      @activity_feed_page_module.settings['custom_event_types'] = true
      if params[:event_type_id] == 'all'
        @activity_feed_page_module.settings['selected_event_types'] = EasyActivity.all_visible_event_types(User.current)
      else
        @activity_feed_page_module.settings['selected_event_types'] = [params[:event_type_id]]
      end
    end

    @events = EpmActivityFeed.events_for_settings(@activity_feed_page_module.settings)

    respond_to do |format|
      format.js
    end
  end

  def get_current_user_activities_count
    respond_to do |format|
      format.json {
        # This should be part of EasyBackgroundService now
        render :json => { :current_activities_count => Rails.env.test? ? 0 : EasyActivity.last_current_user_events_with_defaults_count }
      }
    end
  end

  def discart_all_events
    events = EasyActivity.last_current_user_events_with_defaults
    events.each do |event|
      if event.respond_to?(:mark_as_read)
        event.mark_as_read
      end
    end

    respond_to do |format|
      format.js
    end
  end

  def events_from_activity_feed_module
    if params[:defaults]
      events = EasyActivity.last_current_user_events_with_defaults
    else
      settings = @activity_feed_page_module.settings
      events = EpmActivityFeed.events_for_settings(settings)
    end

    @events_by_day = events.group_by {|event| User.current.time_to_date(event.event_datetime)}

    respond_to do |format|
      format.html
      format.atom {
        render_feed(events)
      }
    end
  end

  private

  def find_activity_feed_page_module
    @activity_feed_page_module = EasyPageZoneModule.find(params[:module_id])
  rescue ActiveRecord::RecordNotFound
    render_404
  end

end
