# encoding: utf-8
module ProjectScoreHelper
  #缺陷数量
  def issue_num project
    project.issues.count
  end

  #缺陷留言数量
  def issue_journal_num project
     project.issue_changes.count
  end

  #新闻数量
  def news_num project
    project.news.count
  end

  #文档数量
  def documents_num project
    project.documents.count
  end

  #代码提交数量
  def changesets_num project
    project.changesets.count
  end

  #讨论区帖子数量
  def board_message_num project
    board_message_count = 0
    project.boards.each do |board|
	    board_message_count += board.messages_count
    end
    board_message_count
  end

  #缺陷得分
  def issue_score project
    i_num = issue_num project
    i_j_num = issue_journal_num project
    i_num * 4 + i_j_num
  end

  # 新闻得分
  def news_score project
    n_num = news_num project
    n_num
  end

  #文档得分
  def documents_score project
    d_num = documents_num(project)
    d_num * 4
  end

  #代码提交得分
  def changesets_score project
    c_num = changesets_num project
    c_num * 4
  end

  #讨论区帖子得分
  def board_message_score project
    b_m_num = board_message_num project
    b_m_num * 2
  end

  #计算项目得分
  def project_scores project
    result = (issue_score project) + (news_score project) + (documents_score project) + (changesets_score project) + (board_message_score project)
    pss = ProjectScore.where("project_id = '#{project.id}'")
    if pss.nil? || pss.count == 0
      ps = ProjectScore.new
      ps.issue_num = issue_num(project)
      ps.board_message_num = board_message_num(project)
      ps.changeset_num = changesets_num(project)
      ps.documents_num = documents_num(project)
      ps.issue_journal_num = issue_journal_num(project)
      ps.news_num = news_num(project)

      ps.score = result
      ps.project = project
      ps.save
    else
      ps = pss.first
      ps.issue_num = issue_num(project)
      ps.board_message_num = board_message_num(project)
      ps.changeset_num = changesets_num(project)
      ps.documents_num = documents_num(project)
      ps.issue_journal_num = issue_journal_num(project)
      ps.news_num = news_num(project)
      ps.score = result
      ps.save
    end
    result
  end

  #读取项目得分
  def red_project_scores project
    grade = 0
    pss = ProjectScore.where("project_id = '#{project.id}'")
    if pss.nil? || pss.count == 0
      grade
    else
      ps = pss.first
      grade = ps.score
      grade
    end
  end

  def get_project_score project
    pss = ProjectScore.where("project_id = '#{project.id}'")
    ps = nil
    if pss.nil? || pss.count == 0
      ps = nil
    else
      ps = pss.first
    end
    ps
  end

end