package test;

import org.jgap.BaseGene;
import org.jgap.Configuration;
import org.jgap.Gene;
import org.jgap.IPersistentRepresentation;
import org.jgap.InvalidConfigurationException;
import org.jgap.RandomGenerator;
import org.jgap.UnsupportedRepresentationException;

public class CalculGene extends BaseGene implements IPersistentRepresentation {

	private static final long serialVersionUID = 2245539380230070425L;

	private Double value = 0d;

	public CalculGene(Configuration a_configuration, Operation t) throws InvalidConfigurationException {
		super(a_configuration);
		setApplicationData(t);
	}

	@Override
	public String toString() {
		return value + " " + getApplicationData().toString();
	}

	@Override
	protected Object getInternalValue() {
		return value;
	}

	@Override
	protected Gene newGeneInternal() {
		try {
			return new CalculGene(getConfiguration(), (Operation) getApplicationData());
		} catch (InvalidConfigurationException e) {
			throw new IllegalStateException();
		}
	}

	public String getPersistentRepresentation() {
		return value + " ";
	}

	public void setValueFromPersistentRepresentation(String a_representation) throws UnsupportedRepresentationException {
		value = Double.parseDouble(a_representation);
	}

	public void applyMutation(int index, double a_percentage) {
		value += Math.random() * a_percentage;
	}

	public void setAllele(Object a_newValue) {
		value = (Double) a_newValue;
	}

	public void setToRandomValue(RandomGenerator a_numberGenerator) {
		value = a_numberGenerator.nextDouble();
	}

	public int compareTo(Object o) {
		if (o != null && o instanceof CalculGene)
			return (int) (value.doubleValue() - ((Double) ((CalculGene) o).getInternalValue()).doubleValue());
		throw new IllegalArgumentException();
	}

}
