module AssetManagementGet
  def retrieve_upload_token(headers = ALW_USER_SERVICE_HEADERS)
    begin
      response = HTTParty.get("#{ENV['ASSET_SERVICE']}/upload-token", headers: headers)
      res = hash_from_response_object(response)
    rescue StandardError => e
      LOG.debug "Module: AssetManagementGet. Method: retrieve_upload_token. Message: #{e.message}"
      raise e
    end
    res
  end

  def retrieve_stream_url(track_id, headers = ALW_USER_SERVICE_HEADERS)
    begin
      response = HTTParty.get("#{ENV['ASSET_SERVICE']}/stream/track/#{track_id}", headers: headers)
      res = hash_from_response_object(response)
    rescue StandardError => e
      LOG.debug "Module: AssetManagementGet. Method: retrieve_stream_url. Message: #{e.message}"
      raise e
    end
    res
  end

  def retrieve_release_assets_info(product_id, headers = ALW_USER_SERVICE_HEADERS)
    begin
      response = HTTParty.get("#{ENV['ASSET_SERVICE']}/asset/product/#{product_id}",
                              headers: headers)
      res = hash_from_response_object(response)
    rescue StandardError => e
      LOG.debug(
        "Module: AssetManagementGet. Method: retrieve_release_assets_info. Message: #{e.message}"
      )
      raise e
    end
    res
  end

  def retrieve_asset_status(query, headers = ALW_USER_SERVICE_HEADERS)
    begin
      response = HTTParty.get("#{ENV['ASSET_SERVICE']}/asset/status",
                              headers: headers, query: query)
      res = hash_from_response_object(response)
    rescue StandardError => e
      LOG.debug "Module: AssetManagementGet. Method: retrieve_asset_status. Message: #{e.message}"
      raise e
    end
    res
  end

  def wait_asset_status_finished(filename, timeout = 20)
    i = 0

    while i != timeout
      res = retrieve_asset_status(filename: filename)
      status = JSON.parse(res[:response])["status"]
      refute_equal(status, "error", "Asset status was error for a file #{filename}")

      return res if status.eql?("finished")
      i += 1
      sleep(10)
    end
    res
  end

  def wait_copy_to_finish(product_id, timeout = 10)
    i = 0

    while i != timeout
      res = retrieve_release_assets_info(product_id)
      response = JSON.parse(res[:response]).extend Hashie::Extensions::DeepFind

      break if !response.deep_find("status").nil? && response.deep_find("status") == "finished"

      i += 2
      sleep(2)
    end
  end

  private

  def hash_from_response_object(response)
    res = { code: 0, response: "" }
    res[:code] = response.code.to_i
    res[:response] = response.body
    res
  end
end
