class RelativeMemo < ActiveRecord::Base
  # attr_accessible :title, :body
  include Redmine::SafeAttributes
  belongs_to :open_source_project, :class_name => "OpenSourceProject", :foreign_key => 'osp_id'
  belongs_to :author, :class_name => "User", :foreign_key => 'author_id'
  
  has_many :tags, :through => :project_tags, :class_name => 'Tag'
  has_many :project_tags, :class_name => 'ProjectTags'
  
  has_many :relation_topics, :class_name => 'RelativeMemoToOpenSourceProject'
  
  has_many :no_uses, :as => :no_use, :dependent => :delete_all
  
  has_many :bugs_to_osp, :class_name => 'BugToOsp', :foreign_key => 'relative_memo_id', :dependent => :destroy
  
  
  acts_as_taggable 

  validates_presence_of :subject
  #validates :content, presence: true
  # validates_length_of :subject, maximum: 50
  #validates_length_of :content, maximum: 3072
  validate :cannot_reply_to_locked_topic, :on => :create
  validates_uniqueness_of :osp_id, :scope => [:subject, :content]

  acts_as_tree :counter_cache => :replies_count, :order => "#{RelativeMemo.table_name}.created_at ASC"
  acts_as_attachable
  belongs_to :last_reply, :class_name => 'RelativeMemo', :foreign_key => 'last_reply_id'
  # acts_as_searchable :column => ['subject', 'content'],
  #           #:include => { :forum => :p}
  #           #:project_key => "#{Forum.table_name}.project_id"
  #           :date_column => "#{table_name}.created_at"
  
  # acts_as_event :title => Proc.new {|o| "#{o.forum.name}: #{o.subject}"},
          # :datetime => :updated_at,
          # # :datetime => :created_at,
          # :description => :content,
          # :author => :author,
          # :type => Proc.new {|o| o.parent_id.nil? ? 'Memo' : 'Reply'},
          # :url => Proc.new {|o| {:controller => 'memos', :action => 'show', :forum_id => o.forum_id}.merge(o.parent_id.nil? ? {:id => o.id} : {:id => o.parent_id, :r => o.id, :anchor => "reply-#{o.id}"})}
  # acts_as_activity_provider :author_key => :author_id,
                # :func => 'memos',
                # :timestamp => 'created_at'
                
                # :find_options => {:type => 'memos'}
  # acts_as_watchable

  safe_attributes "author_id",
          "subject",
          "content",
          "osp_id",
          "last_memo_id",
          "lock",
          "sticky",
          "parent_id",
          "replies_count",
          "is_quote"

  after_create :add_author_as_watcher, :reset_counters!
  # after_update :update_memos_forum
  after_destroy :reset_counters!
  # after_create :send_notification
  # after_save :plusParentAndForum
  # after_destroy :minusParentAndForum

  # scope :visible, lambda { |*args|
  #   includes(:forum => ).where()
  # }

  def cannot_reply_to_locked_topic
    errors.add :base, l(:label_memo_locked) if root.locked? && self != root
  end
  
  def short_content(length = 25)
    str = "^(.{,#{length}})[^\n\r]*.*$"
    content.gsub(Regexp.new(str), '\1...').strip if content
  end

  # def update_memos_forum
  #   if forum_id_changed?
  #     Message.update_all({:board_id => board_id}, ["id = ? OR parent_id = ?", root.id, root.id ])
  #     Forum.reset_counters!(forum_id_was)
  #     Forum.reset_counters!(forum_id)
  #   end
  # end
  
  
  scope :no_use_for, lambda { |user_id|
              { :include => :no_uses,
                :conditions => ["#{NoUse.table_name}.user_id = ?", user_id] }
            }
  
  # 获取帖子的回复          
  def replies
    memos = RelativeMemo.where("parent_id = ?", id)
  end
    
  def no_use_for?(user)
    self.no_uses.each do |no_use|
      if no_use.user_id == user.id
        return true
      end 
    end
    false
  end
  
  def set_no_use(user, flag=true)
    flag ? set_filter(user) : remove_filter(user)
  end
  
  def set_filter(user)
    self.no_uses << NoUse.new(:user => user)
  end
  
  def remove_filter(user)
    return nil unless user && user.is_a?(User)
    NoUse.delete_all "no_use_type = '#{self.class}' AND no_use_id = #{self.id} AND user_id = #{user.id}"
  end

  def reset_counters!
    if parent && parent.id
      RelativeMemo.update_all({:last_reply_id => parent.children.maximum(:id)}, {:id => parent.id})
      parent.update_attribute(:updated_at, Time.now)
    end
    # forum.reset_counters!
  end

  def sticky?
    sticky == 1
  end

  def replies
    RelativeMemo.where("parent_id = ?", id)
  end

  def locked?
    self.lock
  end
  
  def editable_by? user
    # user && user.logged? || (self.author == usr && usr.allowed_to?(:edit_own_messages, project))
    user.admin?
  end

  # def destroyable_by? user
    # (user && user.logged? && (Forum.find(self.forum_id).creator_id == user.id) ) || user.admin?
    # #self.author == user || user.admin?
  # end

  def deleted_attach_able_by? user
    (user && user.logged? && (self.author == user) ) || user.admin?
  end

  private

  def add_author_as_watcher
    Watcher.create(:watchable => self.root, :user => author)
  end

  def send_notification
    if Setting.notified_events.include?('message_posted')
      Mailer.run.message_posted(self)
    end
  end

  # def plusParentAndForum
    # @forum = Forum.find(self.forum_id)
    # @forum.memo_count = @forum.memo_count.to_int + 1
    # @forum.last_memo_id = self.id
    # if self.parent_id
      # @parent_memo = Memo.find_by_id(self.parent_id)
      # @parent_memo.last_reply_id = self
      # @parent_memo.replies_count = @parent_memo.replies_count.to_int + 1
      # @parent_memo.save
    # else
      # @forum.topic_count = @forum.topic_count.to_int + 1
    # end
    # @forum.save
  # end

  # def minusParentAndForum
    # @forum = Forum.find(self.forum_id)
    # @forum.memo_count = @forum.memo_count.to_int - 1
    # @forum.memo_count = 0 if @forum.memo_count.to_int < 0
    # # @forum.last_memo_id = Memo.reorder('created_at ASC').find_all_by_forum_id(self.forum_id).last.id
    # if self.parent_id
      # @parent_memo = Memo.find_by_id(self.parent_id)
      # # @parent_memo.last_reply_id = Memo.reorder('created_at ASC').find_all_by_parent_id(self.parent_id).last.id
      # @parent_memo.replies_count = @parent_memo.replies_count.to_int - 1
      # @parent_memo.replies_count = 0 if @parent_memo.replies_count.to_int < 0
      # @parent_memo.save
    # else
      # @forum.topic_count = @forum.topic_count.to_int - 1
      # @forum.topic_count = 0 if @forum.topic_count.to_int < 0
    # end
    # @forum.save
  # end
end