package com.atlassian.bitbucket.mesh.management;

import com.atlassian.bitbucket.mesh.util.NumberUtils;
import com.fasterxml.jackson.core.JsonGenerator;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

import static java.util.Objects.requireNonNull;

public class SupportUtils {

    public static final String APPLICATION_PROPERTIES_JSON = "application-properties.json";

    private static final Logger log = LoggerFactory.getLogger(SupportUtils.class);

    private SupportUtils() {
        throw new UnsupportedOperationException("SupportProperties is an utility class");
    }

    public static void writeFilesystemObject(@Nonnull JsonGenerator json, @Nonnull Path path) throws IOException {
        requireNonNull(json, "json");
        requireNonNull(path, "path");

        Map<String, String> filesystem = getFilesystemProperties(path);
        if (filesystem != null) {
            json.writePOJOField("filesystem", filesystem);
        }
    }

    private static Map<String, String> getFilesystemProperties(Path path) {
        try {
            FileStore store = Files.getFileStore(path);
            return ImmutableMap.of("name", store.name(),
                   "free-size", NumberUtils.formatSize(store.getUsableSpace()),
                    "total-size", NumberUtils.formatSize(store.getTotalSpace()),
                    "type", store.type());
        } catch (IOException e) {
            log.warn("Could not determine filesystem properties for {}", path, e);
        }
        return null;
    }
}
