package com.atlassian.bitbucket.mesh.git;

import javax.annotation.Nonnull;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;

import static java.util.Objects.requireNonNull;

/**
 * Represents a {@code git} pack file, optionally protected by a {@code .keep} file
 */
public class GitPackFile implements Closeable {

    private final boolean kept;
    private final Path path;

    public GitPackFile(@Nonnull Path path, boolean kept) {
        this.kept = kept;
        this.path = requireNonNull(path, "path");
    }

    /**
     * Removes the keep file that protects the pack from concurrent garbage collection / repack
     *
     * @throws IOException if an I/O error occurs while deleting the keep file
     */
    @Override
    public void close() throws IOException {
        if (kept) {
            try {
                Files.delete(getKeepPath());
            } catch (FileNotFoundException | NoSuchFileException ignored) {
                //If the keep file doesn't exist, no harm
            }
        }
    }

    @Nonnull
    public Path getPath() {
        return path;
    }

    public boolean isKept() {
        return kept;
    }

    private Path getKeepPath() {
        String filename = path.getFileName().toString();
        return path.resolveSibling(filename.substring(0, filename.length() - 5) + ".keep");
    }
}
