class Api::V1::Journals::UpdateService < ApplicationService
  include ActiveModel::Model
  include Api::V1::Issues::Concerns::Checkable
  include Api::V1::Issues::Concerns::Loadable

  attr_reader :container, :journal, :current_user, :notes, :attachment_ids, :receivers_login
  attr_accessor :updated_journal, :atme_receivers

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

  def initialize(container, journal, params, current_user = nil)
    @container = container
    @journal = journal
    @notes = params[:notes]
    @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?
    ActiveRecord::Base.transaction do
      check_attachments(attachment_ids) unless attachment_ids.nil?
      load_attachments(attachment_ids) unless attachment_ids.nil?

      try_lock("Api::V1::Journals::UpdateService:#{@container.id}:#{@journal.id}")
      @updated_journal = @journal
      @updated_journal.notes = notes
      @updated_journal.attachments = @attachments unless attachment_ids.nil?
      @updated_journal.save!
      unlock("Api::V1::containers::Journals::UpdateService:#{@container.id}:#{@journal.id}")

      @updated_journal
    end
  end

end