package cz.senslog.connector.tools.json;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.stream.Collectors;

public final class JsonUtils {

    private static String encodeToUTF8(String string) {
        try {
            return URLEncoder.encode(string, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        }
    }

    public static String jsonObjectToFormURLEncodedString(final JsonObject jsonObject) {
        return jsonObject.asMap().entrySet().stream()
                .map(e -> e.getKey() + "=" + encodeToUTF8(e.getValue().getAsString()))
                .collect(Collectors.joining("&"));
    }
}
