class UpdateProjectScore < ActiveRecord::Migration
  def up
    project_count = Project.all.count / 30 + 2
    transaction do
      for i in 1 ... project_count do i
      Project.page(i).per(30).each do |project|
        puts project.id
        if ProjectScore.where("project_id=?", project.id).first.nil?
          puts "create project ==>#{project.id}"
          ProjectScore.create(:project_id => project.id, :score => false)
        end
        unless project.project_score.nil?
          # update boards
          unless project.boards.first.nil?
            boards_count = project.boards.first.topics.count
            project.project_score.update_attribute(:board_num, boards_count)
          end
          # update boards reply
          unless project.boards.first.nil?
            messages_count = Message.where("board_id =? and parent_id is not ?", project.boards.first.id, nil).count
            project.project_score.update_attribute(:board_message_num, messages_count)
          end
          # update issues
          unless project.issues.nil?
            issues_count = project.issues.count
            project.project_score.update_attribute(:issue_num, issues_count)
          end
          # update issue's journal
          # if !project.project_score.nil? && !project.project_score.issue_journal_num.nil?
          #   project.project_score.update_attribute(:issue_journal_num, project.project_score.issue_journal_num)
          # end
          # update news
          unless project.news.nil?
            news_count = project.news.count
            project.project_score.update_attribute(:news_num, news_count)
          end
          # update attach
          unless project.attachments.nil?
            attachments_count = project.attachments.count
            project.project_score.update_attribute(:attach_num, attachments_count)
          end
          # update commits
          unless project.gpid.nil?
            g = Gitlab.client
            begin
              puts project.id
              count = g.project(project.gpid).commit_count
            rescue
              logger.error("The project's rep is not exit!")
            end
            project.project_score.update_attribute(:changeset_num, count)
          end
        end
      end
      end
    end
  end

  def down
  end
end
