package com.atlassian.bitbucket.mesh.git;

import com.atlassian.bitbucket.mesh.rpc.v1.RpcOsFile;
import com.google.protobuf.ByteString;
import com.google.protobuf.Timestamp;

import javax.annotation.Nonnull;
import java.time.Instant;

import static java.util.Objects.requireNonNull;

public class Reflog {

    private final Instant lastModified;
    private final String refId;
    private final long size;

    public Reflog(@Nonnull String refId, long size, @Nonnull Instant lastModified) {
        this.lastModified = requireNonNull(lastModified, "lastModified");
        this.refId = requireNonNull(refId, "refId");
        this.size = size;
    }

    @Nonnull
    public static Reflog fromOsFile(@Nonnull RpcOsFile osFile) {
        Timestamp timestamp = osFile.getLastModified();
        return new Reflog(osFile.getPath().toStringUtf8(), osFile.getSize(),
                Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos()));
    }

    @Nonnull
    public Instant getLastModified() {
        return lastModified;
    }

    @Nonnull
    public String getRefId() {
        return refId;
    }

    public long getSize() {
        return size;
    }

    @Nonnull
    public RpcOsFile toOsFile() {
        return RpcOsFile.newBuilder()
                .setLastModified(Timestamp.newBuilder()
                        .setSeconds(lastModified.getEpochSecond())
                        .setNanos(lastModified.getNano()))
                .setPath(ByteString.copyFromUtf8(refId))
                .setSize(size)
                .build();
    }
}
