require_dependency "events_hub/application_controller"

module EventsHub
  class GroupsController < ApplicationController
    before_action :set_group, only: [:show, :edit, :update, :settings, :image, :status, :join, :leave, :use_as]

    def show
      @posts = @group.posts.paginate(page: params[:page])
      if params[:event]
        events = Event.where(id: params[:event])
        ids = @posts.select { |post| (post.event_ids & events.ids).present? }.map(&:id)
        @posts = current_user.relevant_posts.where(id: ids)
      end
      @posts = @posts.paginate(page: params[:page], per_page: 15)
      respond_to do |format|
        format.html
        format.js do
          if params[:filter]
            render 'filter'
          else
            render partial: 'posts_feed'
          end
        end
      end
    end

    def new
      @group = Group.new
    end

    def create
      @group = EventsHub::Group.new(group_params)
      @group.owner = current_user
      if @group.save!
        redirect_to @group
      else
        render :new
      end
    end

    def edit
    end

    def update
      if @group.update(group_params)
        redirect_to @group
      else
        render :show
      end
    end

    def index
      @groups = EventsHub::Group.public_groups
    end

    def join
      current_user.create_membership @group
      redirect_to @group
    end

    def leave
      current_user.remove_membership @group
      redirect_to root_path
    end

    def settings
      respond_to do |format|
        format.html
        format.js
      end
    end

    def image
      respond_to do |format|
        format.html
        format.js
      end
    end

    def status
      respond_to do |format|
        format.html
        format.js
      end
    end

    def use_as
      session[:group_id] = @group.id
      redirect_back fallback_location: root_url
    end

    private

      def set_group
        @group = Group.friendly.find(params[:id])
      end

      def group_params
        params.require(:group).permit(:name, :avatar, :summary, :status, :public)
      end
  end
end
