package com.atlassian.bitbucket.mesh.io;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;

import static java.util.Objects.requireNonNull;

public class PathWithAttributes {

    private final Path path;

    private volatile BasicFileAttributes attributes;

    public PathWithAttributes(@Nonnull Path path) {
        this(path, null);
    }

    public PathWithAttributes(@Nonnull Path path, @Nullable BasicFileAttributes attributes) {
        this.attributes = attributes;
        this.path = requireNonNull(path, "path");
    }

    @Nonnull
    public BasicFileAttributes getAttributes() {
        if (attributes == null) {
            try {
                attributes = Files.readAttributes(path, BasicFileAttributes.class);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
        return attributes;
    }

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