/*
 * Copyright (C) 2018, 2019, 2021, 2023 Andrew Gegg
 *
 *	This file is part of the Garden Notebook application
 *
 * The Garden Notebook application is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/gpl.html>.
 */

/*
	Change log
	2.2.0   Support hsqldb dialect
    2.2.5   Improve JSON load - make it faster!
    2.3.0   Retrieve generated keys properly!
            Date handling change - seems to be a MySQL 8 thing.
    2.4.0   Support MS SQLServer
	3.0.0	Support Location field
 			Use DBCommentHandler
	3.1.0	Use jakarta implementation of JSON
*/

package uk.co.gardennotebook.mysql;

import uk.co.gardennotebook.spi.*;

import uk.co.gardennotebook.util.StoryLineTree;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Date;
import java.sql.Timestamp;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import jakarta.json.JsonObject;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.EntryMessage;
import org.apache.logging.log4j.Level;

/**
*
*{@inheritDoc}
*
*	@author	Andy Gegg
*	@version	3.1.0
*	@since	1.0
*/
final class WildlifeBuilder implements IWildlifeBuilder
{
	private static final Logger LOGGER = LogManager.getLogger();

	private IWildlife oldInstance = null;

	private final boolean newInstance;

	private boolean changedAncestor = false;

	private int id;
	private int wildlifeSpeciesId;
	private boolean changedWildlifeSpeciesId = false;

	/*
	 *	Where the observation took place.
	 */
	private Integer locationId;
	private boolean changedLocationId = false;

	private LocalDate date;
	private boolean changedDate = false;
	private String variety;
	private boolean changedVariety = false;
	private LocalDateTime lastUpdated;
	private LocalDateTime created;
	private boolean somethingChanged = false;

	private boolean changedComments = false;

	private DBCommentHandler commentHandler;	//	compiler will not allow declaration as final

	/**
	*	constructor to use for a new entry
	*/
	WildlifeBuilder()
	{
		this(null);
	}

	/**
	*	constructor to use to edit or delete an existing entry
	*
	*	@param	oldVal	the existing item to modify or delete; if null a new entry will be created
	*/
	WildlifeBuilder(final IWildlife oldVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("constructor(): oldVal={}", oldVal);
		if (oldVal == null || oldVal.getKey() == null || !(oldVal.getKey() instanceof Integer))
		{
			newInstance = true;
			oldInstance = null;
			this.id = -1;
			//	need to set the default value for dates
			this.date = LocalDate.now();
			commentHandler = new DBCommentHandler(NotebookEntryType.WILDLIFE);
			return;
		}

		newInstance = false;
		oldInstance = oldVal;

		Wildlife baseObj;
		if (oldVal instanceof Wildlife)
		{
			baseObj = (Wildlife)oldVal;
			this.id = baseObj.getId();
			this.wildlifeSpeciesId = baseObj.getWildlifeSpeciesId();
			this.locationId = baseObj.getLocationId();
			this.date = baseObj.getDate();
			this.variety = baseObj.getVariety().orElse(null);
			this.lastUpdated = baseObj.getLastUpdated();
			this.created = baseObj.getCreated();
		}
		else
		{
			Object ky = oldVal.getKey();
			if (ky == null) return;
			if (ky instanceof Integer)
				this.id = (Integer)ky;
			ky = oldVal.getWildlifeSpecies();
			if (ky == null)
			{
				this.wildlifeSpeciesId = 0;
			}
			else
			{
				this.wildlifeSpeciesId = ((IWildlifeSpecies)ky).getKey();
			}
			ky = oldVal.getLocation().orElse(null);
			if (ky == null)
			{
				this.locationId = null;
			}
			else
			{
				this.locationId = ((ILocation)ky).getKey();
			}
			this.date = oldVal.getDate();
			this.variety = oldVal.getVariety().orElse(null);
			this.lastUpdated = oldVal.getLastUpdated();
			this.created = oldVal.getCreated();
		}
		commentHandler = new DBCommentHandler(NotebookEntryType.WILDLIFE, this.id);
		LOGGER.traceExit();
	}	//	constructor()

	/**
	*	give the (new) value of wildlifeSpeciesId
	*
	*	@param	newVal	the new value
	*	@return	this Builder
	*/
	IWildlifeBuilder wildlifeSpeciesId(final int newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("wildlifeSpeciesId(): oldVal={}, newVal={}", this.wildlifeSpeciesId, newVal);
		if (this.wildlifeSpeciesId == newVal) return this;
		this.wildlifeSpeciesId = newVal;
		changedWildlifeSpeciesId = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}
	@Override
	public IWildlifeBuilder wildlifeSpecies(final IWildlifeSpecies newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("wildlifeSpecies(): oldVal={}, newVal={}", this.wildlifeSpeciesId, newVal);
		if (newVal == null) return this;
		if (this.wildlifeSpeciesId == newVal.getKey()) return this;
		this.wildlifeSpeciesId = newVal.getKey();
		changedWildlifeSpeciesId = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}

	/**
	 *	give the (new) value of locationId
	 *
	 *	@param	newVal	the new value
	 *	@return	this Builder
	 */
	IWildlifeBuilder locationId(final int newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("location(): oldVal={}, newVal={}", this.locationId, newVal);
		if (this.locationId == newVal) return this;
		this.locationId = newVal;
		changedLocationId = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}

	@Override
	public IWildlifeBuilder location(final ILocation newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("location(): oldVal={}, newVal={}", this.locationId, newVal);
		if ((newVal == null) && (this.locationId == null)) return this;
		if ((newVal != null) && (this.locationId != null) && (this.locationId.equals(newVal.getKey()))) return this;
		if (newVal == null)
		{
			this.locationId = null;
		}
		else
		{	//	non-null value
			this.locationId = newVal.getKey();
		}
		changedLocationId = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}

	@Override
	public IWildlifeBuilder date(final LocalDate newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("date(): oldVal={}, newVal={}", this.date, newVal);

		if (newVal == null) return this;
		if (newVal.equals(this.date)) return this;
		this.date = newVal;
		changedDate = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}

	@Override
	public IWildlifeBuilder variety(final String newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("variety(): oldVal={}, newVal={}", this.variety, newVal);

		if (newVal == null && this.variety == null) return this;
		if (newVal != null && this.variety != null && newVal.equals(this.variety)) return this;
		this.variety = newVal;
		changedVariety = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}

	@Override
	public IWildlifeBuilder addComment(final String... newVals)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("addComment[array]()");

		commentHandler.addComment(newVals);
		changedComments = commentHandler.isChangedComments();
		LOGGER.traceExit("addComment");
		return this;
	}

	@Override
	public IWildlifeBuilder addComment(final List<String> newVals)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("addComment<list>()");

		commentHandler.addComment(newVals);
		changedComments = commentHandler.isChangedComments();
		LOGGER.traceExit("addComment");
		return this;
	}

	/**
	*	remove a comment from this item
	*
	*	@param	newVals	the comment to remove.  If the comment does not exist, this is a null-op
	*	@return	 this Builder
	*/
	IWildlifeBuilder deleteComment(int... newVals)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("deleteComment()");

		commentHandler.deleteComment(newVals);
		changedComments = commentHandler.isChangedComments();
		LOGGER.traceExit(log4jEntryMsg);
		return this;
	}

	@Override
	public IWildlifeBuilder deleteComment(final IComment... newVals)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("deleteComment()");

		commentHandler.deleteComment(newVals);
		changedComments = commentHandler.isChangedComments();
		LOGGER.traceExit(log4jEntryMsg);
		return this;
	}

	@Override
	public IWildlifeBuilder deleteComment(final List<IComment> vals)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("deleteComment()");

		if (vals == null) return this;

		commentHandler.deleteComment(vals);
		changedComments = commentHandler.isChangedComments();
		LOGGER.traceExit(log4jEntryMsg);
		return this;
	}

	@Override
	public IWildlifeBuilder changeComment(final IComment base, final String comment)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("changeComment()");

		commentHandler.changeComment(base, comment);
		changedComments = commentHandler.isChangedComments();
		LOGGER.traceExit(log4jEntryMsg);
		return this;
	}

	@Override
	public IWildlifeBuilder changeComment(final IComment base, final LocalDate date)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("changeComment()");

		commentHandler.changeComment(base, date);
		changedComments = commentHandler.isChangedComments();
		LOGGER.traceExit(log4jEntryMsg);
		return this;
	}

	@Override
	public IWildlifeBuilder changeComment(final IComment base, final LocalDate date, final String comment)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("changeComment()");

		commentHandler.changeComment(base, date, comment);
		changedComments = commentHandler.isChangedComments();
		LOGGER.traceExit(log4jEntryMsg);
		return this;
	}

	@Override
	public IWildlife save() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("save(): somethingChanged: {}, newInstance: {}, changedComments: {}, changedAncestor: {}",
                                                                somethingChanged, newInstance, changedComments, changedAncestor);

		if (!somethingChanged && !newInstance && !changedComments && !changedAncestor)
		{
			LOGGER.traceExit("nothing changed");
			return MySQLCache.cacheWildlife.get(this.id);
		}

		if (newInstance)
		{
			doInsert();
		}
		else if (somethingChanged)
		{
			doUpdate();
		}

		if (changedComments)
		{
			commentHandler.setParentId(this.id);
			commentHandler.save();
		}

// mark cache as dirty
		if (!newInstance &&(somethingChanged || changedComments))
		{
			MySQLCache.cacheWildlife.remove(this.id);
		}
// populate the cache
		new WildlifeLister().id(this.id).fetch();
		IWildlife newValue = MySQLCache.cacheWildlife.get(this.id);
		if (oldInstance != null)
		{
			oldInstance.flagReplaced(newValue);
		}

	//	tell any parent beans the child list has mutated
	//	only additions and deletions matter, other changes will be reflected through the child bean
		if (newInstance)
		{
			MySQLCache.cacheWildlifeSpecies.get(wildlifeSpeciesId).flagChildAdded(newValue);
		}
		else
		{	//	updated
			if (changedWildlifeSpeciesId)
			{
				if (oldInstance != null)
				{
					MySQLCache.cacheWildlifeSpecies.get(oldInstance.getWildlifeSpecies().getKey()).flagChildDeleted(oldInstance);
				}
				MySQLCache.cacheWildlifeSpecies.get(newValue.getWildlifeSpecies().getKey()).flagChildAdded(newValue);
			}
			if (changedLocationId)
			{
				if (oldInstance != null)
				{
					oldInstance.getLocation().ifPresent(item -> MySQLCache.cacheLocation.get(item.getKey()).flagChildDeleted(oldInstance) );
				}
				newValue.getLocation().ifPresent(item -> MySQLCache.cacheLocation.get(item.getKey()).flagChildAdded(newValue) );
			}
		}

		//	stop multiple saves!
		oldInstance = null;

		somethingChanged = false;
		changedComments = false;
		changedAncestor = false;
		changedWildlifeSpeciesId = false;
		changedLocationId = false;
		changedDate = false;
		changedVariety = false;

		LOGGER.traceExit(log4jEntryMsg);
		return newValue;
	}	//	save()

	@Override
	public boolean needSave()
	{
		return somethingChanged || changedComments || changedAncestor;
	}	// needSave()

	@Override
	public boolean canSave()
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("canSave(): newInstance={}", newInstance);

		if (!needSave())
		{//	save() will be a null-op but that's OK
			return true;
		}
		if (this.wildlifeSpeciesId <= 0)
		{
			LOGGER.debug("wildlifeSpeciesId not set");
			return false;
		}
		if (this.date == null ||
			this.date == LocalDate.MAX ||
			this.date == LocalDate.MIN)
		{
			LOGGER.debug("date not set");
			return false;
		}
		return true;
	}	// canSave()

	@Override
	public boolean canDelete() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("canDelete(): newInstance={}", newInstance);

		return LOGGER.traceExit(log4jEntryMsg, !newInstance);
	}	// canDelete()

	@Override
	public void delete() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("delete(): newInstance={}", newInstance);

		if (newInstance) return;
		if (!canDelete()) return;

		int res = 0;
		String query = "delete from wildlife where wildlifeId = " + this.id;
LOGGER.debug("delete(): query: {}", query);
		try (	Connection conn = DBConnection.getConnection();
				Statement stmt = conn.createStatement();	)
		{
			res = stmt.executeUpdate(query);
LOGGER.debug("delete(): result: {}", res);
			// tidy up dependencies with nullable keys
			if (res > 0) {
				query = "delete from comment where ownerId = " + this.id + " and ownerType = 'WI'";
				int res2 = stmt.executeUpdate(query);
LOGGER.debug("delete() comments: result: {}", res2);
			}
			stmt.close();
		}catch (SQLException ex) {
			LOGGER.error("delete(): SQLException: errorCode: {}, SQLstate: {}, message: {}", ex.getErrorCode(), ex.getSQLState(), ex.getMessage());
			throw new GNDBException(ex, ex.getErrorCode(), ex.getSQLState());
		}
		if (res > 0)
		{
			oldInstance.flagDeleted();
			MySQLCache.cacheWildlife.remove(this.id);
	//	tell any parent beans the child list has mutated
	//	only additions and deletions matter, other changes will be reflected through the child bean
			MySQLCache.cacheWildlifeSpecies.get(oldInstance.getWildlifeSpecies().getKey()).flagChildDeleted(oldInstance);
		}
		oldInstance = null;
LOGGER.traceExit(log4jEntryMsg);
	}	// delete()

	private void doUpdate() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("doUpdate(): newInstance={}, somethingChanged={}", newInstance, somethingChanged);

		if (newInstance) return;
		if (!somethingChanged) return;
		StringBuilder query = new StringBuilder("update wildlife set ");
		if (changedWildlifeSpeciesId)
		{
			query.append("wildlifeSpeciesId = ?, ");
		}

		if (changedLocationId)
		{
			query.append("locationId = ?, ");
		}

		if (changedDate)
		{
			query.append("date = ?, ");
		}

		if (changedVariety)
		{
			query.append("variety = ?, ");
		}

		query.delete(query.length()-2, query.length());
		query.append(" where wildlifeId = ").append(this.id);
LOGGER.debug("doUpdate(): query={} ", query.toString());
		try (	Connection conn = DBConnection.getConnection();
				PreparedStatement stmt = conn.prepareStatement(query.toString());	)
		{
			int paramIx = 1;
			if (changedWildlifeSpeciesId)
			{
LOGGER.debug("doUpdate(): param {}={}", paramIx, this.wildlifeSpeciesId);
				stmt.setInt(paramIx++, this.wildlifeSpeciesId);
			}

			if (changedLocationId)
			{
				if (this.locationId == null)
				{
					LOGGER.debug("doUpdate(): param {} null", paramIx);
					stmt.setNull(paramIx++, java.sql.Types.INTEGER);
				}
				else
				{
					LOGGER.debug("doUpdate(): param {}={}", paramIx, this.locationId);
					stmt.setInt(paramIx++, this.locationId);
				}
			}

			if (changedDate)
			{
LOGGER.debug("doUpdate(): param {}={}", paramIx, Date.valueOf(this.date));
				stmt.setDate(paramIx++, Date.valueOf(this.date), java.util.Calendar.getInstance()); //  2.3.0
			}

			if (changedVariety)
			{
				if (this.variety == null)
				{
LOGGER.debug("doUpdate(): param {} null", paramIx);
					stmt.setNull(paramIx++, java.sql.Types.VARCHAR);
				}
				else
				{
LOGGER.debug("doUpdate(): param {}={}", paramIx, this.variety);
					stmt.setString(paramIx++, this.variety);
				}
			}

			stmt.executeUpdate();

		}catch (SQLException ex) {
			LOGGER.error("doUpdate(): SQLException: errorCode: {}, SQLstate: {}, message: {}", ex.getErrorCode(), ex.getSQLState(), ex.getMessage());
			throw new GNDBException(ex, ex.getErrorCode(), ex.getSQLState());
		}
LOGGER.traceExit(log4jEntryMsg);
	}	// doUpdate

	private void doInsert() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("doInsert(): newInstance={}", newInstance);

		if (!newInstance) return;
		if (!canSave())
		{
			throw LOGGER.throwing(Level.ERROR, new IllegalStateException("doInsert(): save criteria not met"));
		}
		if (!this.changedWildlifeSpeciesId)
		{
			throw LOGGER.throwing(Level.ERROR, new IllegalStateException("WildlifeBuilder: doInsert(): wildlifeSpeciesId unspecified"));
		}

		StringBuilder query = new StringBuilder("insert into wildlife (");
		query.append("wildlifeSpeciesId, ");
		query.append("date, ");

		if (changedVariety)
		{
			query.append("variety, ");
		}

		if (changedLocationId)
		{
			query.append("locationId, ");
		}

		query.replace(query.length()-2, query.length(), ") values (");
		query.append("?, ");
		query.append("?, ");
		if (changedVariety)
		{
			query.append("?, ");
		}

		if (changedLocationId)
		{
			query.append("?, ");
		}

		query.replace(query.length()-2, query.length(), ")");
LOGGER.debug("doInsert(): query={}", query.toString());

		try (	Connection conn = DBConnection.getConnection();
				PreparedStatement stmt = conn.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS); )
		{
			int paramIx = 1;
LOGGER.debug("doInsert(): param {}={}", paramIx, this.wildlifeSpeciesId);
			stmt.setInt(paramIx++, this.wildlifeSpeciesId);
LOGGER.debug("doInsert(): param {}={}", paramIx, Date.valueOf(this.date));
			stmt.setDate(paramIx++, Date.valueOf(this.date), java.util.Calendar.getInstance()); //  2.3.0
			if (changedVariety) {
				if (this.variety == null)
				{
LOGGER.debug("doInsert(): param {} null", paramIx);
					stmt.setNull(paramIx++, java.sql.Types.VARCHAR);
				}
				else
				{
LOGGER.debug("doInsert(): param {}={}", paramIx, this.variety);
					stmt.setString(paramIx++, this.variety);
				}
			}

			if (changedLocationId) {
				if (this.locationId == null)
				{
					LOGGER.debug("doInsert(): param {} null", paramIx);
					stmt.setNull(paramIx++, java.sql.Types.INTEGER);
				}
				else
				{
					LOGGER.debug("doInsert(): param {}={}", paramIx, this.locationId);
					stmt.setInt(paramIx++, this.locationId);
				}
			}

			stmt.executeUpdate();

			ResultSet rs = stmt.getGeneratedKeys();
			rs.next();
			int newId = rs.getInt(1);
LOGGER.debug("doInsert(): newId: {}", newId);
			this.id = newId;
		}catch (SQLException ex) {
			LOGGER.error("doInsert(): SQLException: errorCode: {}, SQLstate: {}, message: {}", ex.getErrorCode(), ex.getSQLState(), ex.getMessage());
			throw new GNDBException(ex, ex.getErrorCode(), ex.getSQLState());
		}

LOGGER.traceExit(log4jEntryMsg);
	}	// doInsert

	/**
     * Process the whole JSON array from a DUMP
     * 
     *  @param newVal    a list of JSON objects representing PlantSpecies as output by a JSON DUMP
     * 
     *	@throws	GNDBException	If the underlying MySQL database throws SQLException it is translated to this.
     *				The causal SQLException can be retrieved by <code>getCause()</code>
     * 
     * @since 2.2.5
     */
    void restoreJsonDump(List<JsonObject> newVal) throws GNDBException
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("restoreJsonDump(list JSON)");
        
        if (newVal.isEmpty())
            return;

		StringBuilder query = new StringBuilder("insert into wildlife (");
        query.append("wildlifeId, ");
		query.append("wildlifeSpeciesId, ");
		query.append("locationId, ");
		query.append("date, ");
		query.append("variety, ");
		query.append("lastUpdated, ");
		query.append("created) ");
        if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.hsqldb)
        {
            query.append(" overriding system value ");
        }
        query.append(" values (");
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.append("?) ");
LOGGER.debug("restoreJsonDump(): query={}", query.toString());

		try (	Connection conn = DBConnection.getConnection();
				PreparedStatement stmt = conn.prepareStatement(query.toString());	)
		{
            conn.setAutoCommit(false);
            if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
            {
                conn.createStatement().execute("SET IDENTITY_INSERT wildlife ON");
            }

            int txCount = 0;
            for (JsonObject jo : newVal)
            {
                if (!"DUMP".equals(jo.getString("JsonMode", "DUMP")))
                {
                    LOGGER.error("Wildlife DUMP object is not DUMP");
                    throw new IllegalArgumentException("Wildlife DUMP object is not DUMP");
                }
                if (!"Wildlife".equals(jo.getString("JsonNBClass", "Wildlife")))
                {
                    LOGGER.error("Wildlife DUMP object is not Wildlife");
                    throw new IllegalArgumentException("Wildlife DUMP object is not Wildlife");
                }
                Wildlife ps = new Wildlife(jo);
                if (ps.getId() <= 0)
                {//this forces the value of the id field.  The >0 test is a bodge.
                    LOGGER.error("Wildlife DUMP object does not have an id");
                    throw new IllegalArgumentException("Wildlife DUMP object does not have an id");
                }
                
                int paramIx = 1;
LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getId());
                    stmt.setInt(paramIx++, ps.getId());

LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getWildlifeSpeciesId());
                stmt.setInt(paramIx++, ps.getWildlifeSpeciesId());

				if (ps.getLocationId() == null)
				{
					LOGGER.debug("restoreJsonDump(): param {} null", paramIx);
					stmt.setNull(paramIx++, java.sql.Types.INTEGER);
				}
				else
				{
					LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getLocationId());
					stmt.setInt(paramIx++, ps.getLocationId());
				}

				LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getDate());
                stmt.setDate(paramIx++, Date.valueOf(ps.getDate()), java.util.Calendar.getInstance()); //  2.3.0
                
                if (!ps.getVariety().isPresent())
                {
LOGGER.debug("restoreJsonDump(): param {} null", paramIx);
                    stmt.setNull(paramIx++, java.sql.Types.VARCHAR);
                }
                else
                {
LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getVariety().get());
                    stmt.setString(paramIx++, ps.getVariety().get());
                }

LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getLastUpdated());
                stmt.setTimestamp(paramIx++, Timestamp.valueOf(ps.getLastUpdated()));
LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getCreated());
                stmt.setTimestamp(paramIx++, Timestamp.valueOf(ps.getCreated()));
            
                stmt.executeUpdate();

                if (!ps.getComments().isEmpty())
                {
                    if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
                    {
                        conn.createStatement().execute("SET IDENTITY_INSERT wildlife OFF");
                    }
                    CommentBuilder cb = new CommentBuilder(NotebookEntryType.WILDLIFE, ps.getId());
                    cb.doJsonInsert(ps.getComments(), conn);
                    if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
                    {
                        conn.createStatement().execute("SET IDENTITY_INSERT wildlife ON");
                    }
                }

                if (++txCount > 50)
                {
                    conn.commit();
                    txCount = 0;
                }
            }
            conn.commit();
            if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
            {
                conn.createStatement().execute("SET IDENTITY_INSERT wildlife OFF");
            }
		} catch (SQLException ex) {
			LOGGER.error("doJsonInsert(): SQLException: errorCode: {}, SQLstate: {}, message: {}", ex.getErrorCode(), ex.getSQLState(), ex.getMessage());
			throw new GNDBException(ex, ex.getErrorCode(), ex.getSQLState());
		}

	}	// restoreJsonDump(JsonObjects)

	@Override
	public boolean hasAncestor() throws GNDBException
	{
		//	this class does not participate in story lines
		return false;
	}	//	hasAncestor()

	@Override
	public StoryLineTree<? extends INotebookEntry> getAncestors() throws GNDBException
	{
		//	this class does not participate in story lines
		return StoryLineTree.emptyTree();
	}	//	getAncestors()

	@Override
	public IWildlifeBuilder ancestor(IPurchaseItem ancestor) throws GNDBException
	{
		return this;
	}	//	ancestor(PurchaseItem)

	@Override
	public IWildlifeBuilder ancestor(IGroundwork ancestor) throws GNDBException
	{
		return this;
	}	//	ancestor(Groundwork)

	@Override
	public IWildlifeBuilder ancestor(IAfflictionEvent ancestor) throws GNDBException
	{
		return this;
	}	//	ancestor(AfflictionEvent)

	@Override
	public IWildlifeBuilder ancestor(IHusbandry ancestor) throws GNDBException
	{
		return this;
	}	//	ancestor(Husbandry)

	@Override
	public IWildlifeBuilder ancestor(ISaleItem ancestor) throws GNDBException
	{
		return this;
	}	//	ancestor(SaleItem)

	@Override
	public boolean hasDescendant() throws GNDBException
	{
		//	this class does not participate in story lines
		return false;
	}	//	hasDescendant()

	@Override
	public StoryLineTree<? extends INotebookEntry> getDescendants() throws GNDBException
	{
		//	this class does not participate in story lines
		return StoryLineTree.emptyTree();
	}	//	getDescendants()

	@Override
	public boolean addDescendant(IPurchaseItem descendant) throws GNDBException
	{
		return false;
	}	//	addDescendant(PurchaseItem)

	@Override
	public boolean addDescendant(IGroundwork descendant) throws GNDBException
	{
		return false;
	}	//	addDescendant(Groundwork)

	@Override
	public boolean addDescendant(IAfflictionEvent descendant) throws GNDBException
	{
		return false;
	}	//	addDescendant(AfflictionEvent)

	@Override
	public boolean addDescendant(IHusbandry descendant) throws GNDBException
	{
		return false;
	}	//	addDescendant(Husbandry)

	@Override
	public boolean addDescendant(ISaleItem descendant) throws GNDBException
	{
		return false;
	}	//	addDescendant(SaleItem)

}

