/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.channel.cc.orchestrator.commons.messaging;

import java.nio.ByteBuffer;
import java.util.UUID;

import com.scytl.products.ov.channel.cc.orchestrator.commons.polling.ReactiveResultsHandler;
import com.scytl.products.ov.commons.messaging.MessageListener;

/**
 * Implementation of {@link MessageListener} which notifies a
 * {@link ReactiveResultsHandler} instance about of the readiness of the results.
 */
public final class ResultsReadyListener implements MessageListener {
    
    private final ReactiveResultsHandler<?> handler;
    
    /**
     * Constructor.
     * 
     * @param handler
     */
    public ResultsReadyListener(ReactiveResultsHandler<?> handler) {
        this.handler = handler;
    }

    @Override
    public void onMessage(Object message) {
        byte[] bytes = (byte[]) message;
        if (bytes.length != Long.BYTES * 2) {
            throw new IllegalArgumentException("Invalid UUID encoding.");
        }
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        long mostSigBits = buffer.getLong();
        long leastSigBits = buffer.getLong();
        UUID correlationId = new UUID(mostSigBits, leastSigBits);
        handler.resultsReady(correlationId);
    }
}
