Then(/^the project should contains environment '(\w+)'$/) do |env|
  body = JSON.parse(last_response.body)
  assert !body["deploy_envs"].detect{|e| e["identifier"] == env}.nil?, "Project has no environment '#{env}'"
end

Then(/^the servers list should be saved$/) do
  body = JSON.parse(last_response.body)
  store_parameter("servers_list", body)
end

Then(/^the servers list should contains new (\w+) server$/) do |provider|
  body = JSON.parse(last_response.body)
  id = (body.map{|s| s["id"]} - get_parameter("servers_list").map{|s| s["id"]}).first
  assert !id.nil?, "New element in servers list not found"
  store_parameter("#{provider}_server_id", id)
end

When(/^I unreserve new '(\w+)' server$/) do |provider|
  steps %{
    When I send POST '/v3/server/#{get_parameter("#{provider}_server_id")}/unreserve' query
  }
end

When(/^I reserve new '(\w+)' server$/) do |provider|
  steps %{
    When I send POST '/v3/server/#{get_parameter("#{provider}_server_id")}/reserve' query
  }
end

When(/^I pause new '(\w+)' server$/) do |provider|
  steps %{
    When I send POST '/v3/server/#{get_parameter("#{provider}_server_id")}/pause' query
  }
  sleep(5)
end

When(/^I unpause new '(\w+)' server$/) do |provider|
  steps %{
    When I send POST '/v3/server/#{get_parameter("#{provider}_server_id")}/unpause' query
  }
end

When(/^TODO: I deploy new '(\w+)' server$/) do |provider|
  steps %{
    When I send POST '/v3/server/#{get_parameter("#{provider}_server_id")}/deploy' query
  }
end

When(/^I delete '(\w+)' new server$/) do |provider|
  steps %{
    When I send DELETE '/v3/server/#{get_parameter("#{provider}_server_id")}' query
  }
end

Then(/^sleep '(\d+)' seconds$/) do |s|
  sleep(s.to_i)
end

Then(/^waiting background task$/) do
  body = JSON.parse(last_response.body)
  id = body[0]
  store_parameter("task_id", id)
  status = nil
  loop do
    sleep(5)
    status = get("/v3/task/#{id}/status", {}, {'Accept' => 'application/json'}).body.strip
    break if status == "completed" or status == "failed"
  end
  assert(status == "completed", "Error while server creation, task '#{id}'")
end

Then(/^store id in variable '(.*)'$/) do |name|
  body = JSON.parse(last_response.body)
  store_parameter(name, body["id"])
end

When(/^I unbootstrap new '(\w+)' server$/) do |provider|
  steps %{
    When I send POST '/v3/server/#{get_parameter("#{provider}_server_id")}/unbootstrap' query
  }
end

When(/^I bootstrap new '(\w+)' server$/) do |provider|
  steps %{
    When I send POST '/v3/server/#{get_parameter("#{provider}_server_id")}/bootstrap' query
  }
end

