/*
 * 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.engine.types;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;

/**
 * A plain old string.  Very permissive, will allow any input to be converted
 * in to a string.
 */
public class Text extends SimpleType {

  public static final Charset IO_CHARSET = Charset.forName("UTF-8");
  private static final int HOUSEKEEPING_BYTES = 2;

  /**
   * Convert the given value in to a string
   * @throws CoercionException if value is null
   */
  @Override
  public Object coerce(Object value) {
    checkForNull(value);
    return value.toString();
  }

  @Override
  public Class<?> internalType() {
    return String.class;
  }

  @Override
  public int estimateSize(Object entry) {
    String string = (String) entry;
    return HOUSEKEEPING_BYTES + string.length() * 2;
  }

  @Override
  public void toBytes(DataOutputStream os, Object toWrite) throws IOException {
    String stringToWrite = (String) toWrite;
    // NB this used to use DataOutputStream's writeUTF method, which had some java idiosyncracies - switched to use
    // "true" utf8, so that it works with our cpython plugin
    byte[] utf8Bytes = stringToWrite.getBytes(IO_CHARSET);
    os.writeShort(utf8Bytes.length);
    os.write(utf8Bytes);
  }

  @Override
  public Object fromBytes(DataInputStream in) throws IOException {
    int expectedLength = in.readShort();
    byte[] utf8Bytes = new byte[expectedLength];
    int totalRead = 0;

    while (totalRead != expectedLength) {
      int read = in.read(utf8Bytes, totalRead, expectedLength - totalRead);
      if (read == -1) {
        throw new EOFException("unexpected EOF reading text");
      }
      totalRead += read;
    }

    return new String(utf8Bytes, IO_CHARSET);
  }

  @Override
  public Object read(ByteBuffer buffer) {
    int byteLength = buffer.getInt();
    byte[] bytes = new byte[byteLength];
    buffer.get(bytes);

    return new String(bytes, IO_CHARSET);
  }

  @Override
  public void write(ByteBuffer buffer, Object value) {
    String string = (String) value;
    byte[] bytes = string.getBytes(IO_CHARSET);

    buffer.putInt(bytes.length);
    buffer.put(bytes);
  }

}
