class SubDocumentComment < ActiveRecord::Base
  attr_accessible :content, :creator_id, :locked, :org_subfield_id, :parent_id, :reply_id, :sticky, :sub_domain_id, :title

  include Redmine::SafeAttributes
  include ApplicationHelper
  belongs_to :sub_domain
  belongs_to :creator, :class_name => 'User', :foreign_key => 'creator_id'
  acts_as_tree :order => "#{SubDocumentComment.table_name}.sticky asc, #{SubDocumentComment.table_name}.created_at desc"
  acts_as_attachable
  has_many :org_acts, :class_name => 'OrgActivity',:as =>:org_act ,:dependent => :destroy
  after_create :document_save_as_sub_activity
  after_update :update_activity
  validates_presence_of :content

  #动态的更新
  private
  def update_activity
    org_activity = OrgActivity.where("org_act_type='SubDocumentComment' and org_act_id =?", id).first
    if org_activity
      org_activity.updated_at = Time.now
      org_activity.save
    end
  end

  def document_save_as_sub_activity
    if(self.parent().nil?)
      self.org_acts << OrgActivity.new(:user_id => User.current.id, :container_id => self.sub_domain.id, :container_type => 'SubDomain')
    else
      act = OrgActivity.where("org_act_type='SubDocumentComment' and org_act_id =?", self.root.id).first
      act.update_attributes(:updated_at => self.updated_at)
    end
  end
end
