class Api::V1::Journals::CreateService < ApplicationService
  include ActiveModel::Model
  include Api::V1::Issues::Concerns::Checkable
  include Api::V1::Issues::Concerns::Loadable
  #
  attr_reader :container, :current_user, :notes, :parent_id, :reply_id, :attachment_ids, :receivers_login
  attr_accessor :created_journal, :atme_receivers

  validates :notes, :container, :current_user, presence: true

  def initialize(container, params, current_user=nil)
    @container = container 
    @notes = params[:notes]
    @parent_id = params[:parent_id]
    @reply_id = params[:reply_id]
    @attachment_ids = params[:attachment_ids]
    @receivers_login = params[:receivers_login]
    @current_user = current_user
  end

  def call 
    raise Error, errors.full_messages.join(", ") unless valid?
    raise Error, "请输入回复的评论ID" if parent_id.present? && !reply_id.present?
    ActiveRecord::Base.transaction do 
      check_parent_journal(parent_id) if parent_id.present? 
      check_parent_journal(reply_id) if reply_id.present? 
      check_attachments(attachment_ids) unless attachment_ids.nil?
      # check_atme_receivers(receivers_login) unless receivers_login.nil?
      load_attachments(attachment_ids) unless attachment_ids.nil?
      # load_atme_receivers(receivers_login) unless receivers_login.nil?

      try_lock("Api::V1::Journals::CreateProjectService:#{@container.id}")
      @created_journal = @container.journals.new(journal_attributes)
      @created_journal.attachments = @attachments unless attachment_ids.blank?
      
      @created_journal.save!
      # @container.save!

      unlock("Api::V1::Journals::CreateProjectService:#{@container.id}")

      @created_journal
    end
  end 

  private 

  def journal_attributes 
    journal_attributes = {
      notes: notes,
      user_id: current_user.id
    }

    journal_attributes.merge!({parent_id: parent_id}) if parent_id.present?
    journal_attributes.merge!({reply_id: reply_id}) if reply_id.present?
    
    journal_attributes
  end

end