class ConversationsController < ApplicationController

  before_filter :require_login
  before_filter :find_conversation, except: [:index]

  # Get chat converstion messages of current user.
  def index
    params[:per_page] ||= 10
    @conversations = current_user.conversations.with_messages.order('updated_at DESC').page(params[:page]).per(params[:per_page])
    respond_to do |format|
      format.js {}
      format.html do
        if @conversations.first
          redirect_to conversation_path(@conversations.first)
        else
          redirect_to root_path, alert: 'No conversations found!'
        end
      end
    end
  end

  # Shows all conversation messages of current user and reset unread messages count.
  def show
    params[:per_page] ||= 10
    @conversation.reset_unread_messages_count!(current_user)
    @conversations = current_user.conversations.with_messages.order('updated_at DESC')
    @messages = @conversation.messages.includes({sent_receipt: {user: :profile_image}})
    @messages = @messages.includes(:attachment).order('id DESC').paginate(params[:page], params[:per_page], params[:offset])
    respond_to do |format|
      format.json {render json: @messages.reverse}
      format.html {}
    end
  end

  # Send message and trigger event typing if user is typing the message.
  def reply
    if params[:attachment].blank? and params[:typing] and params[:typing] != 'false'
      @conversation.trigger_typing_event_except(current_user, params[:typing])
      render json: {success: true}
    else
      if params[:msg].present? or params[:attachment].present?
        if message = @conversation.reply(params[:msg], params[:attachment])
          render json: {success: true, message_id: message.id}
        else
          render json: {success: false}
        end
      else
        render json: {success: false}
      end
    end
  end

  # Reset unread messages count.
  def read
    @conversation.reset_unread_messages_count!(current_user)
    ActsAsTenant.current_tenant.pusher_configuration.client.trigger_async("private-user-#{current_user.id}", 'message-count', {conversation_id: @conversation.id, unread_conversations_count: current_user.cached_message_count})
    render nothing: true
  end

  # Shows conversation participants wthout rendering the page.
  def participants
    render layout: false
  end

  private

  def find_conversation
    @conversation = current_user.conversations.find(params[:id])
  end
end
