# added by fq

class JournalReply < ActiveRecord::Base
  attr_accessible :journal_id, :reply_id, :user_id
  
  belongs_to :user
  belongs_to :journal
  after_create :send_journal_messages
  
  def self.add_reply(journal_id, reply_id, user_id)
    self.create(:journal_id => journal_id, :reply_id => reply_id, :user_id => user_id)
  end

  def send_journal_messages
    journal = self.journal
    replier = User.find(self.reply_id)
    receivers = []
    # 被回复的人发送消息
    if journal.user_id != self.reply_id && self.reply_id != journal.issue.author_id && self.reply_id != journal.issue.assigned_to_id
      receivers << replier
    end
    if journal.user_id != journal.issue.author_id && self.reply_id != journal.issue.author_id
      receivers << self.journal.issue.author
    end
    # journal_forge_messages = ForgeMessage.new
    receivers.each do |r|
      journal.forge_messages << ForgeMessage.new(:user_id =>r.id, :project_id => journal.issue.project_id, :viewed => false)
    end

    #   if self.user_id != self.journal_reply.user_id
    #     receivers << self.journal_reply.user_id
    #   end
    # # 给缺陷发布者发送
    #   if self.user_id != self.issue.author_id && self.journal_reply.user_id != self.issue.author_id
    #     receivers << self.issue.author_id
    #   end
  end
end
