package org.allmyinfo.json.reader;

import java.util.Date;
import java.util.Stack;

import org.eclipse.jdt.annotation.NonNull;

public abstract class BaseJsonParseEventHandler implements JsonParseEventHandler {
	private final @NonNull Stack<Receiver> stack = new Stack<>();

	@Override
	public void onNumber(final double value) throws JsonReaderSemanticException {
		final Receiver receiver = pop();
		if (receiver instanceof NumberReceiver) {
			final NumberReceiver numberReceiver = (NumberReceiver) receiver;
			numberReceiver.receive(value);
		}
		else if (receiver instanceof DateReceiver) {
			final DateReceiver dateReceiver = (DateReceiver) receiver;
			dateReceiver.receive(new Date((long) value));
		}
		else
			throw new IllegalStateException();
	}

	@Override
	public void onString(final @NonNull String value) {
		final Receiver receiver = pop();
		if (!(receiver instanceof StringReceiver))
			throw new IllegalStateException();
		final StringReceiver stringReceiver = (StringReceiver) receiver;
		stringReceiver.receive(value);
	}

	@Override
	public void onBoolean(final boolean value) {
		final Receiver receiver = pop();
		if (!(receiver instanceof BooleanReceiver))
			throw new IllegalStateException();
		final BooleanReceiver booleanReceiver = (BooleanReceiver) receiver;
		booleanReceiver.receive(value);
	}

	@Override
	public void onNull() {
		final Receiver receiver = pop();
		if (!(receiver instanceof NullReceiver))
			throw new IllegalStateException();
		final NullReceiver nullReceiver = (NullReceiver) receiver;
		nullReceiver.receiveNull();
	}

	protected Receiver pop() {
		return stack.pop();
	}

	protected Receiver peek() {
		return stack.peek();
	}

	protected void push(final Receiver receiver) {
		stack.push(receiver);
	}

	protected Receiver get(final int index) {
		return stack.get(index);
	}

	protected int stackSize() {
		return stack.size();
	}
}
