package com.atlassian.bitbucket.mesh.config;

import org.springframework.core.env.Environment;

import javax.annotation.Nonnull;
import java.time.Duration;

import static com.atlassian.bitbucket.mesh.rpc.ManagedConfigurationProperties.*;

class DefaultStorageConfig implements StorageConfig {

    private final Environment environment;

    private volatile Settings current;

    DefaultStorageConfig(Environment environment) {
        this.environment = environment;

        current = new Settings(environment);
    }

    @Nonnull
    @Override
    public int getCleanupThreads() {
        return current.cleanupThreads;
    }

    @Nonnull
    @Override
    public Duration getPartitionCleanupDelay() {
        return current.partitionCleanupDelay;
    }

    @Nonnull
    @Override
    public Duration getTempExpiry() {
        return current.tempExpiry;
    }

    void reload() {
        current = new Settings(environment);
    }

    private static class Settings {

        private final int cleanupThreads;
        private final Duration partitionCleanupDelay;
        private final Duration tempExpiry;

        Settings(Environment environment) {
            cleanupThreads = environment.getProperty(STORAGE_CLEANUP_THREADS, Integer.class, 1);
            partitionCleanupDelay =
                    Duration.ofSeconds(environment.getProperty(STORAGE_PARTITION_CLEANUP_DELAY, Long.class, 3600L));
            tempExpiry = Duration.ofHours(environment.getProperty(STORAGE_TEMP_EXPIRY, Long.class, 72L));
        }
    }
}
