package com.livingworld.data.serialization;

import java.util.Properties;

/**
 * {@link PersistenceReader} backed by a {@link Properties} object.
 *
 * <p>All key lookups are namespaced by a caller-supplied prefix, mirroring
 * the convention used by {@link PropertiesPersistenceWriter}. Missing keys
 * return the supplied default value rather than throwing.</p>
 */
public final class PropertiesPersistenceReader implements PersistenceReader {

    private final Properties props;
    private final String prefix;

    public PropertiesPersistenceReader(Properties props, String prefix) {
        this.props = props;
        this.prefix = prefix;
    }

    @Override
    public String readString(String key, String defaultValue) {
        String value = props.getProperty(prefix + key);
        return value != null ? value : defaultValue;
    }

    @Override
    public int readInt(String key, int defaultValue) {
        String value = props.getProperty(prefix + key);
        return value != null ? Integer.parseInt(value) : defaultValue;
    }

    @Override
    public long readLong(String key, long defaultValue) {
        String value = props.getProperty(prefix + key);
        return value != null ? Long.parseLong(value) : defaultValue;
    }

    @Override
    public double readDouble(String key, double defaultValue) {
        String value = props.getProperty(prefix + key);
        return value != null ? Double.parseDouble(value) : defaultValue;
    }

    @Override
    public boolean readBoolean(String key, boolean defaultValue) {
        String value = props.getProperty(prefix + key);
        return value != null ? Boolean.parseBoolean(value) : defaultValue;
    }
}
