namespace :jenkins do
  namespace :myshixun do
    desc "ping ce"
    task :game_build => :environment do
      100.times do
        puts "start"
        game = Game.find_by_identifier('lzwg7ute3ki5')
        myshixun = game.myshixun
        game_challenge = game.challenge
        rep_identify = Repository.where(:myshixun_id => myshixun.id, :type => "Repository::Gitlab").first.try(:identifier)
        gitlab_address = Redmine::Configuration['gitlab_address']
        gitUrl = gitlab_address.to_s+"/"+myshixun.owner.to_s+"/"+ rep_identify + "."+"git"
        gitUrl = Base64.encode64(gitUrl)
        taskId = game.id
        jobName = "myshixun_#{myshixun.id}"
        if game.status == 2
          game.update_attribute(:status, 0)
        end
        # 过关后重评不更新状态
        jenkins_shixuns = Redmine::Configuration['jenkins_shixuns']
        step = game_challenge.try(:position)
        params = {:jobNameForInstance  => "#{jobName}", :buildID => "#{taskId}", :step => "#{step}",  :instanceGitURL  => "#{gitUrl}", :instanceChallenge  => "#{step}", :resubmit => nil}
        uri = URI("#{jenkins_shixuns}/jenkins-exec/api/buildJobForInstance")
        puts("post data time is #{Time.now}")
        res = Net::HTTP.post_form(uri, params).body
        res = JSON.parse(res)
        puts("post data end time is #{Time.now}")
        if (res && res['code'] != 0)
          puts("error")
          puts("current time is #{Time.now}")
        end
        puts("game over")
        puts("waiting for 120s")
        sleep(120);
      end
    end
  end
end