class Api::V1::Issues::JournalsController < Api::V1::BaseController
  before_action :require_login, except: [:index, :children_journals]
  before_action :require_public_and_member_above
  before_action :load_issue
  before_action :load_journal, only: [:children_journals, :update, :destroy]
  before_action :check_journal_operate_permission, only: [:update, :destroy]

  def index 
    @object_result = Api::V1::Issues::Journals::ListService.call(@issue, query_params, current_user)
    @total_journals_count = @object_result[:total_journals_count]
    @total_operate_journals_count = @object_result[:total_operate_journals_count]
    @total_comment_journals_count = @object_result[:total_comment_journals_count]
    @journals = kaminary_select_paginate(@object_result[:data])
  end

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

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

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

  def destroy 
    TouchWebhookJob.set(wait: 5.seconds).perform_later('IssueComment', @issue&.id, current_user.id, @journal.id, 'deleted', JSON.parse(@journal.to_builder.target!))
    if @journal.destroy!
      render_ok
    else 
      render_error("删除评论失败！")
    end
  end

  private

  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 load_issue 
    @issue = @project.issues.issue_issue.where(project_issues_index: params[:index]).where.not(id: params[:index]).take || @project.issues.issue_issue.find_by_id(params[:index])
    if @issue.blank?
      render_not_found("疑修不存在!")
    end
  end

  def load_journal
    @journal = Journal.find_by_id(params[:id])
    return render_not_found("评论不存在！") unless @journal.present?
  end

  def check_journal_operate_permission 
    return render_forbidden("您没有操作权限！") unless @project.member?(current_user) || current_user.admin? || @issue.user == current_user || @journal.user == current_user || @journal.parent_journal&.user == current_user
  end

end