/*
 * The file defines an IntegerGene subclass for use with Sudoku puzzles.
 */
//package org.jgap.impl;

import java.util.*;
import org.jgap.*;

/**
 * An IntegerGene implementation that supports an integer values for its allele.
 * But fixes the value of those Genes that are initialized in the puzzle.
 * Upper and lower bounds may optionally be provided to restrict the range
 * of legal values allowed by this Gene instance.
 *
 * @author R. Morelli
 * @since 1.0
 */
public class SudokuGene extends IntegerGene implements Gene {
  /** String containing the CVS revision. Read out via reflection!*/
  private static final String CVS_REVISION = "$Revision: 1.0 $";

  /**  Boolean deterimining whether this is an immutable Gene. */
    protected boolean m_isImmutable = false;
    protected int m_immutableValue;

  /**
   * Constructs a new SudokuGene with default settings. No bounds will
   * be put into effect for values (alleles) of this Gene instance, other
   * than the standard range of integer values.
   *
   * @author R. Morelli
   * @since 1.0
   */
  public SudokuGene() {
    this(Integer.MIN_VALUE, Integer.MAX_VALUE);
  }

  /**
   * Constructs a new SudokuGene with the specified lower and upper
   * bounds for values (alleles) of this Gene instance.
   *
   * @param a_lowerBounds The lowest value that this Gene may possess,
   *                      inclusive.
   * @param a_upperBounds The highest value that this Gene may possess,
   *                      inclusive.
   *
   * @author R. Morelli
   * @since 1.0
   */
  public SudokuGene(int a_lowerBounds, int a_upperBounds) {
    m_lowerBounds = a_lowerBounds;
    m_upperBounds = a_upperBounds;
  }

  /**
   * Constructs a new SudokuGene with the specified lower and upper
   * bounds for values (alleles) of this Gene instance and marks whether
   * it is an immutable Gene, which means its allele cannot be changed
   * after initialization.
   *
   * @param a_lowerBounds The lowest value that this Gene may possess,
   *                      inclusive.
   * @param a_upperBounds The highest value that this Gene may possess,
   *                      inclusive.
   * @param a_isImmutable   True or false
   *
   * @author R. Morelli
   * @since 1.0
   */
  public SudokuGene(int a_lowerBounds, int a_upperBounds, boolean a_isImmutable, int a_immutableValue) {
    m_lowerBounds = a_lowerBounds;
    m_upperBounds = a_upperBounds;
    m_isImmutable = a_isImmutable;
    m_immutableValue = a_immutableValue;
  }

  /**
   * Provides an implementation-independent means for creating new Gene
   * instances. The new instance that is created and returned should be
   * setup with any implementation-dependent configuration that this Gene
   * instance is setup with (aside from the actual value, of course). For
   * example, if this Gene were setup with bounds on its value, then the
   * Gene instance returned from this method should also be setup with
   * those same bounds. This is important, as the JGAP core will invoke this
   * method on each Gene in the sample Chromosome in order to create each
   * new Gene in the same respective gene position for a new Chromosome.
   * <p>
   * It should be noted that nothing is guaranteed about the actual value
   * of the returned Gene and it should therefore be considered to be
   * undefined.
   *
   * @return A new Gene instance of the same type and with the same
   *         setup as this concrete Gene.
   *
   * @author Neil Rostan
   * @since 1.0
   */
  public Gene newGene() {
    return new SudokuGene(m_lowerBounds, m_upperBounds, m_isImmutable, m_immutableValue);
  }

    /**
     * Set's a Gene's value and makes it immutable.
     * @author R. Morelli
     * @since 1.0
     */
    public void setImmutableValue(int a_value) {
	m_immutableValue = a_value;
        m_value = new Integer(a_value);
        m_isImmutable = true;
    }

  /**
   * Retrieves a string representation of this Gene that includes any
   * information required to reconstruct it at a later time, such as its
   * value and internal state. This string will be used to represent this
   * Gene in XML persistence. This is an optional method but, if not
   * implemented, XML persistence and possibly other features will not be
   * available. An UnsupportedOperationException should be thrown if no
   * implementation is provided.
   *
   * @return A string representation of this Gene's current state.
   * @throws UnsupportedOperationException to indicate that no implementation
   *         is provided for this method.
   *
   * @author Neil Rostan
   * @since 1.0
   */
  public String getPersistentRepresentation()
      throws
      UnsupportedOperationException {
    // The persistent representation includes the value, lower bound,
    // and upper bound. Each is separated by a colon.
    // --------------------------------------------------------------
    return toString() + PERSISTENT_FIELD_DELIMITER + m_lowerBounds +
        PERSISTENT_FIELD_DELIMITER + m_upperBounds + ":" + m_isImmutable;
  }

  /**
   * Sets the value and internal state of this Gene from the string
   * representation returned by a previous invocation of the
   * getPersistentRepresentation() method. This is an optional method but,
   * if not implemented, XML persistence and possibly other features will not
   * be available. An UnsupportedOperationException should be thrown if no
   * implementation is provided.
   *
   * @param a_representation the string representation retrieved from a
   *                         prior call to the getPersistentRepresentation()
   *                         method.
   *
   * @throws UnsupportedOperationException to indicate that no implementation
   *         is provided for this method.
   * @throws UnsupportedRepresentationException if this Gene implementation
   *         does not support the given string representation.
   *
   * @author Neil Rostan
   * @since 1.0
   */
  public void setValueFromPersistentRepresentation(String a_representation)
      throws
      UnsupportedRepresentationException {
    if (a_representation != null) {
      StringTokenizer tokenizer =
          new StringTokenizer(a_representation,
                              PERSISTENT_FIELD_DELIMITER);
      // Make sure the representation contains the correct number of
      // fields. If not, throw an exception.
      // -----------------------------------------------------------
      if (tokenizer.countTokens() != 4) {
        throw new UnsupportedRepresentationException(
            "The format of the given persistent representation " +
            "is not recognized: it does not contain four tokens.");
      }
      String valueRepresentation = tokenizer.nextToken();
      String lowerBoundRepresentation = tokenizer.nextToken();
      String upperBoundRepresentation = tokenizer.nextToken();
      String isImmutableRepresentation = tokenizer.nextToken();
      // First parse and set the representation of the value.

      // ----------------------------------------------------
      if (valueRepresentation.equals("null")) {
        m_value = null;
      }
      else {
        try {
          m_value =
              new Integer(Integer.parseInt(valueRepresentation));
        }
        catch (NumberFormatException e) {
          throw new UnsupportedRepresentationException(
              "The format of the given persistent representation " +
              "is not recognized: field 1 does not appear to be " +
              "an integer value.");
        }
      }
      // Now parse and set the lower bound.
      // ----------------------------------
      try {
        m_lowerBounds =
            Integer.parseInt(lowerBoundRepresentation);
      }
      catch (NumberFormatException e) {
        throw new UnsupportedRepresentationException(
            "The format of the given persistent representation " +
            "is not recognized: field 2 does not appear to be " +
            "an integer value.");
      }
      // Now parse and set the upper bound.
      // ----------------------------------
      try {
        m_upperBounds =
            Integer.parseInt(upperBoundRepresentation);
      }
      catch (NumberFormatException e) {
        throw new UnsupportedRepresentationException(
            "The format of the given persistent representation " +
            "is not recognized: field 3 does not appear to be " +
            "an integer value.");
      }
      // Now parse and set the mutability.
      // ----------------------------------
      try {
	  if (isImmutableRepresentation.equals("true"))
	      m_isImmutable = true;
	  else
	      m_isImmutable = false;
      }
      catch (NumberFormatException e) {
        throw new UnsupportedRepresentationException(
            "The format of the given persistent representation " +
            "is not recognized: field 4 does not appear to be " +
            "a String value.");
      }
    }
  }


  /**
   * Sets the value (allele) of this Gene to a random Integer value between
   * the lower and upper bounds (if any) of this Gene.
   *
   * @param a_numberGenerator The random number generator that should be
   *                          used to create any random values. It's important
   *                          to use this generator to maintain the user's
   *                          flexibility to configure the genetic engine
   *                          to use the random number generator of their
   *                          choice.
   *
   * @author Neil Rostan
   * @since 1.0
   */
  public void setToRandomValue(RandomGenerator a_numberGenerator) {
      if (!m_isImmutable)
	  //	  m_value = new Integer((int)((m_upperBounds-m_lowerBounds)*a_numberGenerator.nextDouble()+m_lowerBounds));
	  m_value = new Integer((int)((m_upperBounds-m_lowerBounds+1)*a_numberGenerator.nextDouble()+m_lowerBounds));
      else {
	  m_value = new Integer(m_immutableValue);
	  //	  System.out.println(this.getPersistentRepresentation());
      }
  }

  /**
   * See interface Gene for description
   * @param index ignored (because there is only 1 atomic element)
   * @param a_percentage percentage of mutation (greater than -1 and smaller
   *        than 1).
   *
   * @author Klaus Meffert
   * @since 1.1
   */
  public void applyMutation(int index, double a_percentage) {
    // Don't mutate immutable genes.
    if (m_isImmutable)
       return;          
    double range = (m_upperBounds - m_lowerBounds) * a_percentage;
    if (m_value == null) {
     setAllele(new Integer((int)range+m_lowerBounds));
    }
    else {
      int newValue = (int) Math.round(intValue() + range);
      setAllele(new Integer(newValue));
    }
  }
}
