package com.atlassian.bitbucket.mesh.repository;

import com.atlassian.bitbucket.mesh.management.SupportUtils;
import com.atlassian.bitbucket.mesh.management.SupportInfoProvider;
import com.fasterxml.jackson.core.JsonGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nonnull;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

import static com.atlassian.bitbucket.mesh.io.MoreFiles.pruneStaleFiles;
import static java.util.Objects.requireNonNull;

abstract class AbstractShard implements SupportInfoProvider {

    final Logger log;
    final Path rootDir;

    AbstractShard(@Nonnull Path rootDir) {
        this.rootDir = requireNonNull(rootDir, "rootDir");

        log = LoggerFactory.getLogger(getClass());
    }

    @Override
    public void writeSupportInfo(@Nonnull JsonGenerator json) throws IOException {
        requireNonNull(json, "json").writeStartObject();
        try {
            json.writeStringField("path", rootDir.toString());
            SupportUtils.writeFilesystemObject(json, rootDir);
            writeExtraSupportInfo(json);
        } finally {
            json.writeEndObject();
        }
    }

    @Nonnull
    abstract Path getHooksDir();

    @Nonnull
    Path getRootDir() {
        return rootDir;
    }

    @Nonnull
    abstract ShardState getState();

    @Nonnull
    abstract Path getTemplateDir();

    long getUsableSpace() throws IOException {
        return Files.getFileStore(rootDir).getUsableSpace();
    }

    void pruneStaleConfig(@Nonnull Instant staleTimestamp, @Nonnull Path path) {
        try {
            List<Path> deleted = new ArrayList<>();
            pruneStaleFiles(path, staleTimestamp, false,
                    (deletePath, attributes) -> deleted.add(deletePath));
            if (!deleted.isEmpty()) {
                log.info("Deleted stale configuration files: {}", deleted);
            }
        } catch (IOException e) {
            log.warn("Failed to prune stale files from {}", path, e);
        }
    }

    void writeExtraSupportInfo(JsonGenerator json) throws IOException {
    }
}
