package com.eactive.ext.kjb.util;

import com.eactive.eai.rms.data.entity.man.monitoringProperty.service.MonitoringPropertyService;
import com.eactive.ext.kjb.common.KjbProperty;
import com.eactive.ext.kjb.common.KjbPropertyValue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;

@Slf4j
public class KjbPropertyInjector {
    private final MonitoringPropertyService monitoringPropertyService;
    private final String groupId;


    public KjbPropertyInjector(MonitoringPropertyService monitoringPropertyService, String groupId) {
        this.monitoringPropertyService = monitoringPropertyService;
        this.groupId = groupId;
    }

    public <T> T inject(T property) {
        Class<?> clazz = property.getClass();

        for (Field field : clazz.getDeclaredFields()) {
            KjbPropertyValue anno = field.getAnnotation(KjbPropertyValue.class);

            if (anno != null) {
                String key = anno.key();
                String rawValue = monitoringPropertyService.getPropertyValue(groupId, key, anno.defaultValue());
                Object convertedValue = convertValue(field.getType(), rawValue);

                field.setAccessible(true);
                try {
                    field.set(property, convertedValue);
                } catch (IllegalAccessException e) {
                    log.error("Failed to inject property: {} - {}", field.getName(), key, e);
                    throw new RuntimeException(e);
                }
            }
        }

        return property;
    }


    private static Object convertValue(Class<?> type, String rawValue) {
        if (rawValue == null) return null;
        if (StringUtils.isEmpty(rawValue)) return "";

        if (type == String.class) return rawValue;
        if (type == Integer.class || type == int.class) return Integer.valueOf(rawValue);
        if (type == Long.class || type == long.class) return Long.valueOf(rawValue);
        if (type == Double.class || type == double.class) return Double.valueOf(rawValue);
        if (type == Boolean.class || type == boolean.class) return Boolean.valueOf(rawValue);
        if (type == Float.class || type == float.class) return Float.valueOf(rawValue);
        if (type == Short.class || type == short.class) return Short.valueOf(rawValue);
        if (type == Byte.class || type == byte.class) return Byte.valueOf(rawValue);

        return rawValue;
    }
}
