package eu.dnetlib.openaire.usermanagement;

import com.google.gson.*;

import java.lang.reflect.Type;

public class JwksDeserializer implements JsonDeserializer<Jwks> {

    @Override
    public Jwks deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext)
            throws JsonParseException {

        JsonObject jsonObject = jsonElement.getAsJsonObject();
        if (jsonObject == null) throw new JsonParseException("Jwks not valid.");
        JsonArray jsonArray = jsonObject.getAsJsonArray("keys");

        if (jsonArray == null ) throw new JsonParseException("Jwks not valid.");

        Jwks jwks = new Jwks();
        Key[] keys = new Key[jsonArray.size()];

        Key key = null;
        for (int i = 0; i < jsonArray.size(); i++) {
            key = new Key();
            JsonElement je = jsonArray.get(i);

            if (je == null) throw new JsonParseException("Jwks not valid.");
            if (je.getAsJsonObject().get("kty")==null) throw new JsonParseException("Jwks not valid.");
            key.setKty(je.getAsJsonObject().get("kty").getAsString());

            if (je.getAsJsonObject().get("e")==null) throw new JsonParseException("Jwks not valid.");
            key.setE(je.getAsJsonObject().get("e").getAsString());

            if (je.getAsJsonObject().get("kid")==null) throw new JsonParseException("Jwks not valid.");
            key.setKid(je.getAsJsonObject().get("kid").getAsString());

            if (je.getAsJsonObject().get("alg")==null) throw new JsonParseException("Jwks not valid.");
            key.setAlg(je.getAsJsonObject().get("alg").getAsString());

            if (je.getAsJsonObject().get("n")==null) throw new JsonParseException("Jwks not valid.");
            key.setN(je.getAsJsonObject().get("n").getAsString());
            keys[i] = key;
        }

        jwks.setKeys(keys);
        return jwks;
    }
}
/*
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().registerTypeAdapter(Jwks.class, new JwksDeserializer()).create();

        String jwksJson = "{\n" +
                "  \"keys\": [\n" +
                "    {\n" +
                "      \"kty\": \"RSA\",\n" +
                "      \"e\": \"AQAB\",\n" +
                "      \"kid\": \"05794a3c-a6f5-430c-9822-da4e53597ba5\",\n" +
                "      \"alg\": \"RS256\",\n" +
                "      \"n\": \"hm_OUny05OJEwbGBqPjE7wWvnwTMgqUHJFis_S9nM7hTivXQ_LX9f89RaVcPpXboox81Y8rrfuVwV0nc-FGr_E0FFpI-IwJ_sUUEDwf-5Qxor3LNc_S_5BiPOfFHY7c-R-ablRIAvVTXqwIjcyLVQnaHLjb9XQPf9lBt9sCZ2jN-9HOLztMO3BZWZYIFqvNr8ySKHfVPdlk0Wx3N45KPY0kgxk5RPYW0HLRakSlhIJtqYCJOr2IiDUEMAj9Z9BoWjeUKiAX3E3ZRo-DO1TWcc7feq-0Pei2IBw3lvNpgcBBv1_BlrsZYzQqkKOcDbLAppuhR3inUNhc3G67OuWt8ow\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";
        Jwks jwks = gson.fromJson(jwksJson, Jwks.class);
        for(Key key:jwks.getKeys()) {
            //System.out.println(key.getE());
        }
    }
}
*/