package com.atlassian.bitbucket.mesh.layout;

import com.atlassian.bitbucket.mesh.io.MoreFiles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;

import javax.annotation.Nonnull;
import java.nio.file.Path;
import java.nio.file.Paths;

import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang3.StringUtils.isNotBlank;

public class DefaultHomeSubdirectoryResolver implements HomeSubdirectoryResolver {

    private static final Logger log = LoggerFactory.getLogger(DefaultHomeSubdirectoryResolver.class);
    private static final String PROP_LAYOUT_OVERRIDE = "layout.%s-dir";

    private final Environment environment;

    public DefaultHomeSubdirectoryResolver(Environment environment) {
        this.environment = environment;
    }

    @Nonnull
    @Override
    public Path resolve(@Nonnull Path parent, @Nonnull String name) {
        requireNonNull(parent, "parent");
        requireNonNull(name, "name");

        String override = environment.getProperty(String.format(PROP_LAYOUT_OVERRIDE, name));
        if (isNotBlank(override)) {
            Path result = MoreFiles.mkdir(Paths.get(override));
            log.info("Using '{}' as the '{}' directory", result, name);
            return result;
        }
        return MoreFiles.mkdir(parent.resolve(name));
    }
}
