package oving5;

import java.util.Iterator;
import java.util.function.BinaryOperator;

public class BinaryComputingIterator {
	private Iterator<Double> iterator1;
	private Iterator<Double> iterator2;

	private Double default1;
	private Double default2;

	private BinaryOperator<Double> operator;

	BinaryComputingIterator(Iterator<Double> iterator1, Iterator<Double> iterator2, BinaryOperator<Double> operator) {
		if (iterator1 == null || iterator2 == null || operator == null) {
			throw new IllegalArgumentException("argument cannot be null");
		}
		this.iterator1 = iterator1;
		this.iterator2 = iterator2;
		this.operator = operator;
	}

	BinaryComputingIterator(Iterator<Double> iterator1, Iterator<Double> iterator2, Double default1, Double default2,
			BinaryOperator<Double> operator) {
		if (iterator1 == null || iterator2 == null || operator == null) {
			throw new IllegalArgumentException("argument cannot be null");
		}
		this.iterator1 = iterator1;
		this.iterator2 = iterator2;
		this.operator = operator;
		this.default1 = default1;
		this.default2 = default2;
	}

	boolean hasNext() {
		if (!iterator1.hasNext() && !iterator2.hasNext()) {
			return false;
		}
		if ((iterator1.hasNext() || default1 != null) && (iterator2.hasNext() || default2 != null)) {
			return true;
		}
		return false;
	}

	Double next() {
		if (hasNext()) {
			Double a = 0.0;
			if (iterator1.hasNext()) {
				a = iterator1.next();
			} else {
				a = default1;
			}

			Double b = 0.0;
			if (iterator2.hasNext()) {
				b = iterator2.next();
			} else {
				b = default2;
			}

			return operator.apply(a, b);
		}
		throw new IllegalArgumentException("empty things");
	}
}
