package com.alterdekim.game.message.amf;

import com.alterdekim.game.message.SerializerUtils;

import java.lang.reflect.Field;
import java.util.List;

public class AMFMapper {
    public static <T> T deobfuscate(List<AMFObject> objects, Class<T> valueType) throws Exception {
        List<Field> fields = SerializerUtils.getPrivateFields(valueType);
        T obj = valueType.getDeclaredConstructor().newInstance();
        for( Field field : fields ) {
            AMFObject object = objects.stream()
                    .filter(o -> checkTypeEquality(o.getType(), field.getType().getCanonicalName()))
                    .findFirst()
                    .orElse(null);
            if( object == null ) continue;
            field.set(obj, object.getRaw());
            objects.remove(object);
        }
        return obj;
    }

    private static boolean checkTypeEquality(AMFValueType type, String typeName) {
        return switch(type) {
            case NUMBER -> typeName.equals("java.lang.Double");
            case BOOLEAN -> typeName.equals("java.lang.Boolean");
            case STRING -> typeName.equals("java.lang.String");
            case OBJECT -> typeName.equals("java.util.Map");
            case MIXED_ARRAY -> typeName.equals("java.util.List");
            default -> false;
        };
    }
}
