package anastore.proto;

import anastore.net.AsyncMessage;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Collections;
import java.util.Set;

/**
 * A reply to a {@link HandshakeReq}.  This is sent by the server
 * whenever a block that is in the client's cache is deprecated.
 */
public class DeprecationRep extends AsyncMessage
{
    public final long start;
    public final long timestamp;
    public transient Set<Long> blocks;

    /**
     * Construct a response containing information about a
     * deprecation.  The start time is used to serialize writes and
     * deprecations on the client, and must be equal to one greater
     * than either the timestamp of the last deprecation message or
     * the timestamp of a write operation.  The set of blocks <i>must
     * not</i> change in the future.
     */
    public DeprecationRep(long start, long timestamp, Set<Long> blocks)
    {
        this.start = start;
        this.timestamp = timestamp;
        this.blocks = Collections.unmodifiableSet(blocks);
    }

    @Override
    public String toString()
    {
        StringBuilder res =
            new StringBuilder("DeprecationRep<start=" + start +
                              ",timestamp=" + timestamp + ",[");
        Util.summarize(res, blocks);
        res.append("]>");
        return res.toString();
    }

    /**
     * Write the deprecation reply to the given output stream, using a
     * compact native-type representation of the id set.
     */
    private void writeObject(ObjectOutputStream s)
        throws IOException 
    {
        s.defaultWriteObject();
        Util.writeSetLong(s, blocks);
    }

    /**
     * Reconstitute the deprecation by reconstructing the id set from
     * the native-type representation in the stream.
     */
    private void readObject(ObjectInputStream s)
        throws IOException, ClassNotFoundException
    {
        s.defaultReadObject();
        blocks = Collections.unmodifiableSet(Util.readSetLong(s));
    }
}
