package upem.net.tcp.nonblocking.chat;

import java.nio.ByteBuffer;

/**
 * Created by carayol on 02/05/16.
 */
public class TwoIntReader implements Reader {

    private static enum State {WAITING_FOR_FIRST,WAITING_FOR_SECOND,ERROR,RETRIEVED,DONE};

    private final ByteBuffer bb;
    private State state;
    private final IntReader intReader;
    private int sum=0;

    public TwoIntReader(ByteBuffer bb) {
        this.bb = bb;
        this.intReader= new IntReader(bb);
        this.state=State.WAITING_FOR_FIRST;
    }




    @Override
    public ProcessStatus process() {
       switch (state){
           case WAITING_FOR_FIRST:
                ProcessStatus intReaderStatus = intReader.process();
                if (intReaderStatus!= ProcessStatus.DONE) {
                    if (intReaderStatus== ProcessStatus.ERROR) {
                        state=State.ERROR;
                    }
                    return intReaderStatus;
                }
                sum=intReader.get();
                intReader.reset();
                state=State.WAITING_FOR_SECOND;  //there is no break to move to WAITING_FOR_SECOND
            case WAITING_FOR_SECOND:
                intReaderStatus = intReader.process();
                if (intReaderStatus!= ProcessStatus.DONE) {
                    if (intReaderStatus== ProcessStatus.ERROR) {
                        state=State.ERROR;
                    }
                    return intReaderStatus;
                }
                sum+=intReader.get();
                intReader.reset();
                state=State.DONE;
                return ProcessStatus.DONE;
           default:
               throw new IllegalStateException("Calling TwoIntReader in state "+state);
       }
    }

    @Override
    public Integer get() {
        if (state!= State.DONE) {
            throw new IllegalStateException("Calling TwoIntReader.get() in state "+state);
        }
        state= State.RETRIEVED;
        return sum;
    }

    @Override
    public void reset() {
        state= State.WAITING_FOR_FIRST;
        sum=0;
        intReader.reset();
    }
}
