class ComponentJournalsController < ApplicationController
  before_action :find_container
  before_action :set_journal, only: [:update, :destroy]
  before_action :check_container_manager, only: [:destroy]


  def index
    @object_result = Api::V1::Journals::ListService.call(@container, query_params, current_user)
    @journals = kaminary_select_paginate(@object_result[:data])
  end

  def children_journals
    @object_results = Api::V1::Journals::ChildrenListService.call(@container, @journal, query_params, current_user)
    @journals = kaminari_paginate(@object_results)
  end

  def create
    @object_result = Api::V1::Journals::CreateService.call(@container, journal_params, current_user)
  end



  def update
    @object_result = Api::V1::Journals::UpdateService.call(@container, @journal, journal_params, current_user)
  end

  def destroy 
    if @journal.destroy
      render_ok
    else 
      render_error("删除评论失败！")
    end
  end

  private

  def find_container
    @container = CompetitionInfo.find_by(identifier: params[:competition_info_id]) || CompetitionInfo.find(params[:competition_info_id])
    tip_exception(403, "你没有权限操作!") if @container.blank?
  end

  def set_journal
    @journal = Journal.find(params[:id])
    unless @journal.present?
      normal_status(-1, "评论不存在")
    end
  end

  def query_params
    params.permit(:category, :keyword, :sort_by, :sort_direction)
  end

  def journal_params
    params.permit(:notes, :parent_id, :reply_id, :attachment_ids => [], :receivers_login => [])
  end

  def check_container_manager
    unless @container.class.name.constantize.method_defined?("is_manager?") && @container.is_manager?(current_user)
      tip_exception(403, "你没有权限操作!") if @journal.user_id != current_user.id
    end
  end


  def kaminary_select_paginate(relation)
    limit = params[:limit] || params[:per_page]
    limit = (limit.to_i.zero? || limit.to_i > 200) ? 200 : limit.to_i
    page  = params[:page].to_i.zero? ? 1 : params[:page].to_i

    relation.page(page).per(limit)
  end

  def limit
    params.fetch(:limit, 15)
  end

  def page
    params.fetch(:page, 1)
  end
  
end