require 'db/mongo/models/job_task'
require 'workers/worker'

module Devops
  module Helpers
    class JobWaiter
      class TimeoutReached < StandardError; end

      INTERVAL = 5

      def initialize(job_id, timeout=5000)
        @job_id, @timeout = job_id, timeout
      end

      def wait
        (@timeout / INTERVAL).times do
          sleep(INTERVAL)
          task = Devops::Model::JobTask.find(@job_id)
          case task.status
          when Worker::STATUS::COMPLETED
            return 0
          when Worker::STATUS::FAILED
            return task.job_result_code
          end
        end
        raise TimeoutReached
      end
    end
  end
end
