/*
 * RiskScape™ Copyright New Zealand Institute for Earth Science Limited
 * (Earth Sciences New Zealand) is distributed for research purposes only
 * under the terms of AGPLv3.
 *
 * RiskScape™ Copyright 2026 New Zealand Institute for Earth Science
 * Limited (Earth Sciences New Zealand). All rights reserved. Source code
 * available under the AGPLv3.
 * 
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option) any
 *  later version.
 * 
 * This program is distributed for RESEARCH PURPOSES ONLY, in the hope that it will
 * be useful for research and education initiatives.
 * 
 * If you are not a researcher, or you are a researcher who wishes to use this
 * program on terms other than AGPLv3 (including those who wish to restrict the
 * distribution of any source code created using this program), please contact:
 * https://riskscape.org.nz
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.  You should have received a copy
 * of the GNU Affero General Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * By way of summary only, under the AGPLv3:
 *     • Permissions of this strongest copyleft license are conditioned
 *       on making available complete source code of licensed works and
 *       modifications, which include larger works using a licensed work,
 *       under the same license.
 *     • Copyright and license notices must be preserved.
 *     • Contributors provide an express grant of patent rights.
 *     • When a modified version is used to provide a service over a
 *       network, the complete source code of the modified version must be made
 *       available.
 */
package nz.org.riskscape.rl.ast;

import java.util.function.BiConsumer;

/**
 * Base class for {@link Expression}s along the same lines as PipelineExpression's BaseExpr - makes sure various object
 * methods get overridden and providing template methods for toSource/toString that would be messy if they were done
 * as default methods on Expression
 *
 * TODO we could probably move this to the dsl package...
 */
abstract class BaseAST implements AST {

  /**
   * Helper method for appending the source of another ast element to a string builder, efficiently if possible.
   */
  protected static void appendSource(AST ast, StringBuilder appendTo) {
    if (ast instanceof BaseAST base) {
      base.appendSource(appendTo);
    } else {
      // NB throw instead?
      appendTo.append(ast.toSource());
    }
  }

  /**
   * Append all the given items to the string builder using the given callback and joining elements.
   * @param <T> the type of items
   * @param appendTo a string builder to append items to as strings
   * @param items the items to append
   * @param callback a function that does the work of appending items to the string builder
   * @param separator items are separated by this character
   * @param open prepended to the string
   * @param close appended to the string
   */
  static <T> void join(
      StringBuilder appendTo,
      Iterable<T> items,
      BiConsumer<StringBuilder, T> callback,
      String separator,
      String open,
      String close
  ) {
    appendTo.append(open);
    boolean first = true;
    for (T item : items) {
      if (!first) {
        appendTo.append(separator);
      }
      callback.accept(appendTo, item);
      first = false;
    }
    appendTo.append(close);
  }

  /**
   * Returns a simplified view of the ast in a source-like fashion, but with a lot of details left out for conciseness
   */
  @Override
  public final String toString() {
    StringBuilder builder = new StringBuilder();

    builder.append(getClass().getSimpleName()).append("[");
    appendString(builder);
    builder.append("]");

    return builder.toString();
  }

  /**
   * Append a simplified string representation to the builder. Default implementation uses appendSource.
   * Subclasses can override to provide a more concise representation.
   */
  protected void appendString(StringBuilder appendTo) {
    appendSource(appendTo);
  }

  /**
   * @return a normalized version of the AST that can be parsed to be exactly the same AST as this
   */
  @Override
  public final String toSource() {
    StringBuilder appendTo = new StringBuilder();
    appendSource(appendTo);
    return appendTo.toString();
  }

  /**
   * Implementers extend this to append their source to the given string builder.  Done via string builder to encourage
   * a more efficient implementation than is possible with concatenating multiple toString calls that typically contruct
   * a string builder anyway.
   */
  protected abstract void appendSource(StringBuilder appendTo);

  // these must be overriden
  @Override
  public abstract boolean equals(Object obj);

  @Override
  public abstract int hashCode();

}
