# encoding: utf-8
module ShixunsHelper

  # 已完成实训所获得的经验值
  def myshixun_exp myshixun
    score = 0
    myshixun.games.each do |game|
      score += game.final_score.to_i < 0 ? 0 : game.challenge.score.to_i
    end
    score
  end

  # 已完成实训所消耗的时间
  def myshixun_spend_time myshixun
    time = myshixun.games.map(&:cost_time).sum
    time
  end

  # 已完成实训的准确率
  def myshixun_accuracy myshixun
    accuracy = 0
    count = 0
    myshixun.games.each do |game|
      count += 1
      accuracy += game.accuracy ? game.accuracy : 0
    end
    accuracy.to_f / count
  end

  # 实训的最终通关时间
  def myshixun_done_time myshixun
    time = ""
    if myshixun.status == 1 || myshixun.games.where(:status => 2).count == myshixun.shixun.challenges.count
      time = myshixun.games.where(:status => 2).map(&:end_time).max
    end
    time
  end

  def had_passed_count

  end

  #显示项目配置菜单
  def show_project_memu user
    if user.allowed_to?(:edit_project, @shixun)
      result = "edit_project"
    elsif user.allowed_to?(:manage_members, @shixun)
      result = "training_task"
    elsif user.allowed_to?(:manage_versions, @shixun)
      result = "manage_versions"
    elsif user.allowed_to?(:manage_repository, @shixun)
      result = "manage_repository"
    end
    result
  end

  def show_shixun_mirror shixun
    mirror_name = ""
    shixun.mirror_repositories.try(:each) do |mirror|
      if mirror_name.blank?
        mirror_name = mirror.type_name
      else
        mirror_name = "#{mirror_name};#{mirror.type_name}"
      end
    end
    return mirror_name
  end

  def generate_script shixun, script
    if script.present?
      source_class_name = []
      challenge_program_name = []
      shixun.challenges.map(&:exec_path).each do |exec_path|
        challenge_program_name << "\"#{exec_path}\""
        if shixun.mirror_name.try(:first) == "Java"
          if exec_path.nil? || exec_path.split("src/")[1].nil?
            source = ""
          else
            source = "\"#{exec_path.split("src/")[1].split(".java")[0]}\""
          end
          source_class_name << source.gsub("/", ".") if source.present?
        end
      end
      script = if script.include?("sourceClassName") && script.include?("challengeProgramName")
                 script.gsub("CHALLENGEPROGRAMNAMES","#{challenge_program_name.reject(&:blank?).join(" ")}").gsub("SOURCECLASSNAMES", "#{source_class_name.reject(&:blank?).join(" ")}")
               else
                 script.gsub("CHALLENGEPROGRAMNAMES","#{challenge_program_name.reject(&:blank?).join(" ")}").gsub("SOURCECLASSNAMES", "#{challenge_program_name.reject(&:blank?).join(" ")}")
               end
    end
    return script
  end

  def had_passed_challenge challenge
    Game.where(:challenge_id => challenge.id, :status => 2).limit(3).reorder("final_score desc")
  end

end