module GamesHelper

  def game_code_init(game_id, path)
    game_code = GameCode.where(:game_id => game_id, :path => path).first
    GameCode.create(:game_id => game_id, :path => path) if game_code.blank?
  end

  # 获取目录下所有文件,返回一个文件名的数组 type是查看文件的类型image表示图片
  # type [[1, "图片"], [2, "apk/exe"], [3, "txt"], [4, "html"], [5, "mp3"], [6, "mp4"]]
  def get_dir_filename(path, type, game_id)
    answer_picture = []
    return answer_picture unless File.directory?(path)

    images_suffix = %w(png jpg gif jpeg bmp pic)
    Dir.foreach(path) do |file|
      next if file == '.' || file == '..'

      extension = file.split(".")[1].try(:downcase)
      if images_suffix.include?(extension) && type == 1
        answer_picture << file
        @type = 'image'
      elsif extension == 'html' && type == 4
        answer_picture << file
        @type = 'html'
      elsif extension == 'txt' && type == 3
        answer_picture << file
        @contents = ''
        f = File.open("#{path}/#{file}", 'r')
        # ... process the file
        f.each_line do |line|
          if line.include?('Your score')
            game = Game.find(game_id)
            max_query_index = game.query_index - 1
            a = line[11, line.length-1].try(:strip)
            outputs = game.outputs.where(:query_index => max_query_index)
            outputs.update_all(:text_scor => a) if outputs.present?
          end
          @contents += "#{line}"
        end
        f.close
        @type = 'txt'
      elsif extension == 'mp3' && type == 5
        answer_picture << file
        @type = 'mp3'
      elsif extension == 'mp4' && type == 6
        answer_picture << file
        @type = 'mp4'
      end
    end

    answer_picture
  end

  def evaluate_actual_output test_set
    if test_set.has_attribute?(:code)
      test_set.try(:compile_success).to_s == '0' && test_set.code.to_s == "-1" ?
          "编译失败,请在测试结果中查看具体的错误信息" : test_set.try(:actual_output)
    end
  end

  def shixun_show_type type
    case type.to_i
    when 1
      "image"
    when 2
      "apk/exe"
    when 3
      "txt"
    when 4
      "html"
    when 5
      "mp3"
    when 6
      "mp4"
    end
  end
end