# Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
# Departamento de Informatica - Universidade Federal do Parana
#
# This file is part of portalmec.
#
# portalmec is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# portalmec is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with portalmec.  If not, see <http://www.gnu.org/licenses/>.

class V1::FeedController < ApplicationController
  include ::Paginator
  include ActivitiesFilterService
  before_action :authenticate_user!

  # GET v1/feed
  # GET v1/feed.json
  # Render all activities that logged user can see
  def index
    activities = paginate activities_followed
    render json: activities
  end

  private

  def activities_followed
    query = "privacy = 'public' and ("
    values = [""]

    # builds a query string to find all relevant activities
    current_user.watching.each do |watching|
      if !watching.respond_to?(:state) || watching.state == "published"
        # Activities that are made by, owned by, or change the object you follow should be found
        query += " (trackable_type = ? and trackable_id = ?) or (owner_type = ? and owner_id = ?) or (recipient_type = ? and recipient_id = ?) or"
        3.times do
          values << watching.class.to_s
          values << watching.id
        end
      end
    end

    values[0] = query[0..-3]+")" # remove trailing "or" on the query
    return PublicActivity::Activity.where(key: activities_filter).where(values).order(created_at: :desc)
  end

end