package meerkat.crypto.dkg.gjkr;

import com.google.protobuf.InvalidProtocolBufferException;
import meerkat.crypto.dkg.comm.MessageUtils;
import meerkat.comm.Channel;
import meerkat.protobuf.Comm;
import meerkat.protobuf.DKG;

/**
 * Created by Tzlil on 3/14/2016.
 */
public class SDKGUserImplAbort<T> extends User<T> {

    public static class AbortException extends RuntimeException {

    }

    final int abortStage;
    int stage;
    public SDKGUserImplAbort(Protocol<T> sdkg, Channel channel, int abortStage) {
        super(sdkg, channel);
        this.abortStage = abortStage;// 1 - 4
        this.stage = 1;
    }

    private void abort(){
        //stopReceiver();
        channel.broadcastMessage(MessageUtils.createMessage(DKG.Payload.Type.ABORT));
        throw new AbortException();
    }

    @Override
    protected void stage1() {
        if(stage < abortStage)
            super.stage1();
        else if(stage == abortStage){
            abort();
        }
        stage++;
    }

    @Override
    protected void stage2() {
        if(stage < abortStage)
            super.stage2();
        else if(stage == abortStage){
            abort();
        }
        stage++;
    }

    @Override
    protected void stage3() {
        if(stage < abortStage)
            super.stage3();
        else if(stage == abortStage){
            abort();
        }
        stage++;
    }

    @Override
    protected void stage4() {
        if(stage < abortStage)
            super.stage4();
        else if(stage == abortStage){
            abort();
        }
        stage++;
    }

    @Override
    public void run() {
        try {
            super.run();
        } catch (AbortException e) {
            // Expected
        }
    }
}
