/*
 * Copyright (C) 2018, 2019, 2021 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.3.0   Retrieve generated keys properly!
    2.4.0   Support MS SQLServer
	3.0.0	Use DBCommentHandler
 */

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.Timestamp;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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.0.0
*	@since	1.0
*/
final class PlantNoteBuilder implements IPlantNoteBuilder
{
	private static final Logger LOGGER = LogManager.getLogger();

	private IPlantNote oldInstance = null;

	private final boolean newInstance;

	private boolean changedAncestor = false;

	private int id;

	/*
	*	This note is for a plant species.  Individual varieties may have their own notes as well as or instead of the variety's notes.
	*/
	private int plantSpeciesId;
	private boolean changedPlantSpeciesId = false;

	/*
	*	If given, plantSpeciesId must also be given; this allows easy retrieval of notes for a species and any variety specific notes.
	*/
	private Integer plantVarietyId;
	private boolean changedPlantVarietyId = false;
	private String title;
	private boolean changedTitle = false;
	private String note;
	private boolean changedNote = 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
	*/
	PlantNoteBuilder()
	{
		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
	*/
	PlantNoteBuilder(final IPlantNote 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;
			commentHandler = new DBCommentHandler(NotebookEntryType.PLANTNOTE);
			return;
		}

		newInstance = false;
		oldInstance = oldVal;

		PlantNote baseObj;
		if (oldVal instanceof PlantNote)
		{
			baseObj = (PlantNote)oldVal;
			this.id = baseObj.getId();
			this.plantSpeciesId = baseObj.getPlantSpeciesId();
			this.plantVarietyId = baseObj.getPlantVarietyId();
			this.title = baseObj.getTitle();
			this.note = baseObj.getNote().orElse(null);
			this.lastUpdated = baseObj.getLastUpdated();
			this.created = baseObj.getCreated();
		}
		else
		{
			Object ky = oldVal.getKey();
			if (ky == null) return;
			this.id = (Integer)ky;
			ky = oldVal.getPlantSpecies();
			if (ky == null)
			{
				this.plantSpeciesId = 0;
			}
			else
			{
				this.plantSpeciesId = ((IPlantSpecies)ky).getKey();
			}
			ky = oldVal.getPlantVariety().orElse(null);
			if (ky == null)
			{
				this.plantVarietyId = null;
			}
			else
			{
				this.plantVarietyId = ((IPlantVariety)ky).getKey();
			}
			this.title = oldVal.getTitle();
			this.note = oldVal.getNote().orElse(null);
			this.lastUpdated = oldVal.getLastUpdated();
			this.created = oldVal.getCreated();
		}
		commentHandler = new DBCommentHandler(NotebookEntryType.PLANTNOTE, this.id);
		LOGGER.traceExit();
	}	//	constructor()

	/**
	*	give the (new) value of plantSpeciesId
	*
	*	@param	newVal	the new value
	*	@return	this Builder
	*/
	IPlantNoteBuilder plantSpeciesId(final int newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("plantSpeciesId(): oldVal={}, newVal={}", this.plantSpeciesId, newVal);
		if (this.plantSpeciesId == newVal) return this;
		this.plantSpeciesId = newVal;
		changedPlantSpeciesId = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}
	@Override
	public IPlantNoteBuilder plantSpecies(final IPlantSpecies newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("plantSpecies(): oldVal={}, newVal={}", this.plantSpeciesId, newVal);
		if (newVal == null) return this;
		if (this.plantSpeciesId == newVal.getKey()) return this;
		this.plantSpeciesId = newVal.getKey();
		changedPlantSpeciesId = true;
		this.plantVarietyId = null;
		changedPlantVarietyId = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}

	/**
	*	give the (new) value of plantVarietyId
	*
	*	@param	newVal	the new value
	*	@return	this Builder
	*/
	IPlantNoteBuilder plantVarietyId(final int newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("plantVarietyId(): oldVal={}, newVal={}", this.plantVarietyId, newVal);
		if (this.plantVarietyId == newVal) return this;
		this.plantVarietyId = newVal;
		changedPlantVarietyId = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}
	@Override
	public IPlantNoteBuilder plantVariety(final IPlantVariety newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("plantVariety(): oldVal={}, newVal={}", this.plantVarietyId, newVal);
		if ((newVal == null) && (this.plantVarietyId == null)) return this;
		if ((newVal != null) && (this.plantVarietyId != null) && (this.plantVarietyId.equals(newVal.getKey()))) return this;
		if (newVal == null)
		{
			this.plantVarietyId = null;
		}
		else
		{	//	non-null value
			this.plantVarietyId = newVal.getKey();
			Integer ps_Id = newVal.getPlantSpecies().getKey();	// cannot be null
			if (!ps_Id.equals(this.plantSpeciesId))	// equals returns false if arg is null
			{
				this.plantSpeciesId = ps_Id;
				changedPlantSpeciesId = true;
			}
		}
		changedPlantVarietyId = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}

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

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

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

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

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

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

	@Override
	public IPlantNoteBuilder 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
	*/
	IPlantNoteBuilder deleteComment(int... newVals)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("deleteComment()");

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

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

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

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

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

	@Override
	public IPlantNoteBuilder 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 IPlantNoteBuilder 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 IPlantNoteBuilder 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 IPlantNote 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.cachePlantNote.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.cachePlantNote.remove(this.id);
		}
// populate the cache
		new PlantNoteLister().id(this.id).fetch();
		IPlantNote newValue = MySQLCache.cachePlantNote.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)
		{
			if (plantVarietyId == null)
			{
				MySQLCache.cachePlantSpecies.get(plantSpeciesId).flagChildAdded(newValue);
			}
			if (changedPlantVarietyId && (plantVarietyId != null) )
			{
				MySQLCache.cachePlantVariety.get(plantVarietyId).flagChildAdded(newValue);
			}
		}
		else
		{	//	updated
			if (changedPlantSpeciesId)
			{
				if (oldInstance != null)
				{
					MySQLCache.cachePlantSpecies.get(oldInstance.getPlantSpecies().getKey()).flagChildDeleted(oldInstance);
				}
				MySQLCache.cachePlantSpecies.get(newValue.getPlantSpecies().getKey()).flagChildAdded(newValue);
			}
			if (changedPlantVarietyId)
			{
				if (oldInstance != null)
				{
					oldInstance.getPlantVariety().ifPresent(item -> MySQLCache.cachePlantVariety.get(item.getKey()).flagChildDeleted(oldInstance) );
				}
				newValue.getPlantVariety().ifPresent(item -> MySQLCache.cachePlantVariety.get(item.getKey()).flagChildAdded(newValue) );
			}
		}

		//	stop multiple saves!
		oldInstance = null;

		somethingChanged = false;
		changedComments = false;
		changedAncestor = false;
		changedPlantSpeciesId = false;
		changedPlantVarietyId = false;
		changedTitle = false;
		changedNote = 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.plantSpeciesId <= 0)
		{
			LOGGER.debug("plantSpeciesId not set");
			return false;
		}
		if (this.title == null ||
			this.title.isEmpty() )
		{
			LOGGER.debug("title 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 plantnote where plantNoteId = " + 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 = 'PN'";
				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.cachePlantNote.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.cachePlantSpecies.get(oldInstance.getPlantSpecies().getKey()).flagChildDeleted(oldInstance);
			oldInstance.getPlantVariety().ifPresent(item -> MySQLCache.cachePlantVariety.get(item.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 plantnote set ");
		if (changedPlantSpeciesId)
		{
			query.append("plantSpeciesId = ?, ");
		}

		if (changedPlantVarietyId)
		{
			query.append("plantVarietyId = ?, ");
		}

		if (changedTitle)
		{
			query.append("title = ?, ");
		}

		if (changedNote)
		{
			query.append("note = ?, ");
		}

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

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

			if (changedTitle)
			{
LOGGER.debug("doUpdate(): param {}={}", paramIx, this.title);
				stmt.setString(paramIx++, this.title);
			}

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

			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.changedPlantSpeciesId)
		{
			throw LOGGER.throwing(Level.ERROR, new IllegalStateException("PlantNoteBuilder: doInsert(): plantSpeciesId unspecified"));
		}
		if (!this.changedTitle)
		{
			throw LOGGER.throwing(Level.ERROR, new IllegalStateException("PlantNoteBuilder: doInsert(): title unspecified"));
		}

		StringBuilder query = new StringBuilder("insert into plantnote (");
		query.append("plantSpeciesId, ");
		query.append("title, ");
		if (changedPlantVarietyId)
		{
			query.append("plantVarietyId, ");
		}

		if (changedNote)
		{
			query.append("note, ");
		}

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

		if (changedNote)
		{
			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.plantSpeciesId);
			stmt.setInt(paramIx++, this.plantSpeciesId);
LOGGER.debug("doInsert(): param {}={}", paramIx, this.title);
			stmt.setString(paramIx++, this.title);
			if (changedPlantVarietyId) {
				if (this.plantVarietyId == null)
				{
LOGGER.debug("doInsert(): param {} null", paramIx);
					stmt.setNull(paramIx++, java.sql.Types.INTEGER);
				}
				else
				{
LOGGER.debug("doInsert(): param {}={}", paramIx, this.plantVarietyId);
					stmt.setInt(paramIx++, this.plantVarietyId);
				}
			}

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

			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

	/**
	*	Used to restore a table from a JSON dump.
	*	The PlantNoteBuilder(oldVal) constructor MUST be used with a PlantNote object created using its JSON constructor.
	*	All fields (including timestamps) are written to the database, no checks are made.
	*
	*	@param	newVal	A PlantNote object created from a JSON object written as a 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>
	*/
	void doJsonInsert(PlantNote newVal) throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("doJsonInsert(): newVal={}", newVal);

		int currId = newVal.getId();
		StringBuilder query = new StringBuilder("insert into plantnote (");
		if (newVal.getId() > 0)
		{//this forces the value of the id field.  The >0 test is a bodge.
			query.append("plantNoteId, ");
		}
		query.append("plantSpeciesId, ");
		query.append("plantVarietyId, ");
		query.append("title, ");
		query.append("note, ");
		query.append("lastUpdated, ");
		query.append("created, ");
//		query.replace(query.length()-2, query.length(), ") values (");
		query.replace(query.length()-2, query.length(), ")");
        if (newVal.getId() > 0 && DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.hsqldb)
        {
            query.append(" overriding system value ");
        }
        query.append(" values (");
		if (newVal.getId() > 0)
		{//this forces the value of the id field.  The >0 test is a bodge.
			query.append(newVal.getId()).append(", ");
		}
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.replace(query.length()-2, query.length(), ")");
LOGGER.debug("doJsonInsert(): query={}", query.toString());

		try (	Connection conn = DBConnection.getConnection();
				PreparedStatement stmt = conn.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS); )
		{
			int paramIx = 1;
LOGGER.debug("doJsonInsert(): param {}={}", paramIx, newVal.getPlantSpeciesId());
			stmt.setInt(paramIx++, newVal.getPlantSpeciesId());
			if (newVal.getPlantVarietyId() == null)
			{
LOGGER.debug("doJsonInsert(): param {} null", paramIx);
				stmt.setNull(paramIx++, java.sql.Types.INTEGER);
			}
			else
			{
LOGGER.debug("doJsonInsert(): param {}={}", paramIx, newVal.getPlantVarietyId());
				stmt.setInt(paramIx++, newVal.getPlantVarietyId());
			}

LOGGER.debug("doJsonInsert(): param {}={}", paramIx, newVal.getTitle());
			stmt.setString(paramIx++, newVal.getTitle());
			if (!newVal.getNote().isPresent())
			{
LOGGER.debug("doJsonInsert(): param {} null", paramIx);
				stmt.setNull(paramIx++, java.sql.Types.VARCHAR);
			}
			else
			{
LOGGER.debug("doJsonInsert(): param {}={}", paramIx, newVal.getNote().get());
				stmt.setString(paramIx++, newVal.getNote().get());
			}

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

            if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
            {
                conn.createStatement().execute("SET IDENTITY_INSERT plantnote ON");
            }
            
            stmt.executeUpdate();

			if (currId <= 0)
			{
                ResultSet rs = stmt.getGeneratedKeys();
				rs.next();
				currId = rs.getInt(1);
LOGGER.debug("doJsonInsert(): currId: {}", currId);
			}
            if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
            {
                conn.createStatement().execute("SET IDENTITY_INSERT plantnote OFF");
            }

            if (!newVal.getComments().isEmpty())
            {
                CommentBuilder cb = new CommentBuilder(NotebookEntryType.PLANTNOTE, currId);
                cb.doJsonInsert(newVal.getComments(), conn);
            }
		}catch (SQLException ex) {
			LOGGER.error("doJsonInsert(): SQLException: errorCode: {}, SQLstate: {}, message: {}", ex.getErrorCode(), ex.getSQLState(), ex.getMessage());
			throw new GNDBException(ex, ex.getErrorCode(), ex.getSQLState());
		}


LOGGER.traceExit(log4jEntryMsg);
	}	// doJsonInsert

	@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 IPlantNoteBuilder ancestor(IPurchaseItem ancestor) throws GNDBException
	{
		return this;
	}	//	ancestor(PurchaseItem)

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

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

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

	@Override
	public IPlantNoteBuilder 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)

}

