package com.ease.gsms.server.model.util;

import com.ease.gsms.server.model.NetworkType;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.function.Function;

public class IDEnumDeserializer extends JsonDeserializer<IDEnum> implements ContextualDeserializer {

    JavaType type;

    public IDEnumDeserializer() {
    }

    public IDEnumDeserializer(JavaType type) {
        this.type = type;
    }

    @SuppressWarnings("unchecked")
    @Override
    public IDEnum deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        Class<Enum> cl = (Class<Enum>) type.getRawClass();
        Class<IDEnum> id = (Class<IDEnum>) type.getRawClass();
        if (jsonParser.getCurrentToken().isStructStart()) {
            String fieldName = jsonParser.nextFieldName();
            jsonParser.nextToken();
            jsonParser.nextToken();
            return (IDEnum) Enum.valueOf(cl, fieldName);
        } else if (jsonParser.getCurrentToken().isNumeric()) {
            try {
                return IDEnum.byId(id, jsonParser.getValueAsInt());
            } catch (Exception e) {
                throw new IOException(e);
            }
        } else {
            return (IDEnum) Enum.valueOf(cl, jsonParser.getValueAsString());
        }
    }

    public JsonDeserializer<?> createContextual(DeserializationContext deserializationContext, BeanProperty beanProperty) throws JsonMappingException {
        JavaType contextualType = deserializationContext.getContextualType();
        return new IDEnumDeserializer(contextualType);
    }
}
