class OpenSourceProject < ActiveRecord::Base
  attr_accessible :name

  include Redmine::SafeAttributes
  has_many :applies, :class_name => "ApplyProjectMaster", :as => :apply, :dependent => :delete_all
  has_many :relation_topics, :class_name => 'RelativeMemoToOpenSourceProject', :foreign_key => 'osp_id', :order => "#{RelativeMemo.table_name}.created_at DESC", :dependent => :destroy
  # has_many :topics, :class_name => 'RelativeMemo', :foreign_key => 'osp_id', :conditions => "#{RelativeMemo.table_name}.parent_id IS NULL", :order => "#{RelativeMemo.table_name}.created_at DESC", :dependent => :destroy
  has_many :topics, :through => :relation_topics, :class_name => 'RelativeMemo'
  # has_many :relative_memos, :class_name => 'RelativeMemo', :foreign_key => 'osp_id', :dependent => :destroy
  has_many :tags, :through => :project_tags, :class_name => 'Tag'
  has_many :project_tags, :class_name => 'ProjectTags'
  has_many :masters, :class_name => 'ApplyProjectMaster', :as => :apply, :dependent => :delete_all, :conditions => "#{ApplyProjectMaster.table_name}.status = 2"
  has_many :admin, :through => :masters, :class_name => 'User'
  has_many :apply_tips, :class_name => 'ApplyProjectMaster', :as => :apply, :dependent => :delete_all, :conditions => "#{ApplyProjectMaster.table_name}.status = 1"
  has_many :applicants, :class_name => 'User', :through => :apply_tips, :source => :user
  
  has_many :bugs_to_osp, :class_name => 'BugToOsp', :foreign_key => 'osp_id', :dependent => :destroy
  has_many :bugs, :through => :bugs_to_osp, :class_name => "RelativeMemo", :order => "#{RelativeMemo.table_name}.created_at DESC"


  validates_uniqueness_of :name

  acts_as_taggable

  scope :applied_by, lambda { |user_id|
    { :include => :apply_project_master,
      :conditions => ["#{ApplyProjectMaster.table_name}.user_id = ?", user_id]
      }
  }
  scope :like, lambda {|arg|
    if arg.blank?
      where(nil)
    else
      pattern = "%#{arg.to_s.strip.downcase}%"
      where("LOWER(name) LIKE :p OR LOWER(description) LIKE :p ", :p => pattern)
    end
  }
  def filter(app_dir, language, created_at)
    filter_app_dir(app_dir).filter_language(language).filter_time(created_at)
  end

  def self.filter(app_dir, language, created_at)
    self.filter_app_dir(app_dir).filter_language(language).filter_time(created_at)
  end

  scope :filter_app_dir, lambda {|args|
    nil
  }

  scope :filter_language, lambda {|*arg|
    if arg[0].nil?
      where(nil)
    else
      tagged_with(arg).order('updated_at desc')
    end
  }

  scope :filter_time, lambda {|args|
    where("YEAR(#{OpenSourceProject.table_name}.created_at) = ?", args) unless args.nil?
  }

  # def filter_app_dir(app_dir)
  # nil
  # end
  #
  # def self.filter_app_dir(app_dir)
  # nil
  # end
  #
  # def filter_language(language)
  # nil
  # end
  #
  # def self.filter_language(language)
  # nil
  # end
  #
  # def filter_time(created_at)
  # nil
  # end
  #
  # def self.filter_time(created_at)
  # nil
  # end

  def short_description(length = 255)
    description.gsub(/^(.{#{length}}[^\n\r]*).*$/m, '\1...').strip if description
    #description.gsub(/<\/?.*?>/,"").html_safe if description
    # 不再使用短描述
    # description
  end

  def applied_by?(user)
    self.applies.each do |apply|
      if apply.user_id == user.id
      return true
      end
    end
    false
  end

  def allowed?(user)
    self.applies.each do |apply|
      if apply.user_id == user.id and apply.status == 2
      return true
      end
    end
    false
  end

  def set_apply(user, flag=true)
    flag ? set_filter(user) : remove_filter(user)
  end

  def set_filter(user)
    self.applies << ApplyProjectMaster.new(:user => user, :status => 1)
  end

  def remove_filter(user)
    return nil unless user && user.is_a?(User)
    ApplyProjectMaster.delete_all "apply_type = '#{self.class}' AND apply_id = #{self.id} AND user_id = #{user.id}"
  end

  def admin?(user)
    if user.admin? or ApplyProjectMaster.find(:all, :conditions => ["user_id = ? and apply_type = 'OpenSourceProject' and apply_id = ? and status = ?", user.id, self.id, 2]).present?
    return true
    else
    return false
    end
  end

  def reset_counters!
    self.class.reset_counters!(id)
  end

  def self.reset_counters!(id)
    osp_id = id.to_i
    # update_all("topic_count = (SELECT COUNT(*) FROM #{RelativeMemo.table_name} WHERE osp_id=#{osp_id} AND parent_id IS NULL)," +
     # " memo_count = (SELECT COUNT(*) FROM #{RelativeMemo.table_name} WHERE osp_id=#{osp_id} AND parent_id IS NOT NULL)," +
     # " last_memo_id = (SELECT MAX(id) FROM #{RelativeMemo.table_name} WHERE osp_id=#{osp_id})",
     # ["id = ?", osp_id])
     update_all("topic_count = (SELECT COUNT(*) FROM #{RelativeMemoToOpenSourceProject.table_name} WHERE osp_id=#{osp_id})", 
     # +
     # " memo_count = (SELECT COUNT(*) FROM #{RelativeMemo.table_name} WHERE osp_id=#{osp_id} AND parent_id IS NOT NULL)," +
     # " last_memo_id = (SELECT MAX(id) FROM #{RelativeMemo.table_name} WHERE osp_id=#{osp_id})",
     ["id = ?", osp_id])
  end
end
