package ru.yandex.qe.dispenser.domain.dao.property;

import java.util.Optional;
import java.util.Set;
import java.util.function.Supplier;

import com.google.common.base.Suppliers;

import ru.yandex.qe.dispenser.domain.property.Property;

public class CachingPropertyReader implements PropertyReader {

    private final PropertyDao propertyDao;

    private final Supplier<PropertyDaoImpl> lazyPropertiesSupplier = Suppliers.memoize(this::getAllProperties)::get;

    public CachingPropertyReader(final PropertyDao propertyDao) {
        this.propertyDao = propertyDao;
    }

    private PropertyDaoImpl getAllProperties() {
        final SimpleMemoryDao result = new SimpleMemoryDao();
        for (final Property.Type<?> type : Property.Type.values()) {
            result.addAll(propertyDao.readAll(type));
        }
        return result;
    }

    @Override
    public Optional<Property> read(final String entityKey, final String propertyKey) {
        return lazyPropertiesSupplier.get().read(entityKey, propertyKey);
    }

    @Override
    public Set<Property> read(final String entityKey) {
        return lazyPropertiesSupplier.get().read(entityKey);
    }

    @Override
    public Set<Property> getAll() {
        return lazyPropertiesSupplier.get().getAll();
    }

    private static class SimpleMemoryDao extends PropertyDaoImpl {
        private void addAll(final Set<Property> properties) {
            for (final Property property : properties) {
                id2obj.put(property.getId(), property);
            }
        }
    }
}
