package meerkat.voting.controller.callbacks;

import meerkat.protobuf.Voting.*;
import meerkat.voting.controller.commands.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * A controller callback for the race-voting request to the UI.
 * Upon receiving the answers for the race questions, the callback registers a new command to process
 * the voter's answers (encrypt and then commit) into the controller's queue.
 * If voter cancelled during the process, a cancelling exception is thrown and a RestartVotingCommand is
 * registered through the onFailure() method
 */
public class VotingCallback extends ControllerCallback<List<BallotAnswer>> {
    protected final static Logger logger = LoggerFactory.getLogger(VotingCallback.class);
    protected final UIElement unsuccessfulVotingMessage;

    public VotingCallback(int requestId,
                          long ballotSerialNumber,
                          LinkedBlockingQueue<ControllerCommand> controllerQueue,
                          UIElement unsuccessfulVotingMessage) {
        super(requestId, ballotSerialNumber, controllerQueue);
        this.unsuccessfulVotingMessage = unsuccessfulVotingMessage;
    }

    @Override
    public void onSuccess(List<BallotAnswer> result) {
        logger.debug("callback for voting returned success");
        enqueueCommand(new EncryptAndCommitBallotCommand(getRequestIdentifier(), getBallotSerialNumber(), result));
    }

    @Override
    public void onFailure(Throwable t) {
        if (t instanceof VoterCancelThrowable) {
            logger.debug("VotingCallback got a cancellation response");
            enqueueCommand(new RestartVotingCommand(getRequestIdentifier(), getBallotSerialNumber()));
        }
        else {
            logger.error("voting initiated a failure: " + t);
            enqueueCommand(new ReportErrorCommand(getRequestIdentifier(),
                    getBallotSerialNumber(),
                    unsuccessfulVotingMessage));
        }
    }
}
