/*
 * 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!
    2.4.0   Support MS SQLServer
    3.0.0	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.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 ProductBuilder implements IProductBuilder
{
	private static final Logger LOGGER = LogManager.getLogger();

	private IProduct oldInstance = null;

	private final boolean newInstance;

	private boolean changedAncestor = false;

	private int id;
	private int productCategoryId;
	private boolean changedProductCategoryId = false;

	/*
	*	The product is plants of this species.
@apiNote
If present, plantVarietyId may or may not be given.  This 'denormalises' the model but enables easy searches for e.g. 'all tomatoes'
	*/
	private Integer plantSpeciesId;
	private boolean changedPlantSpeciesId = false;

	/*
	*	The product is plants of this species.
@apiNote
If present, plantSpeciesId must be given.  This 'denormalises' the model but enables easy searches for e.g. 'all tomatoes'
	*/
	private Integer plantVarietyId;
	private boolean changedPlantVarietyId = false;
	private Integer productBrandId;
	private boolean changedProductBrandId = false;

	/*
	*	For plant like products (seeds, etc) the plant species common name.<BR>
<B>This is unreliable - editing the plant species might not change the value here!</B>
	*/
	private String name;
	private boolean changedName = false;

	/*
	*	For plant-like products (seeds, etc) the plant variety (if present) common name<BR>
<B>This is unreliable - editing the plant variety might not change the value here!</B>
	*/
	private String nameDetail_1;
	private boolean changedNameDetail_1 = false;
	private String nameDetail_2;
	private boolean changedNameDetail_2 = false;
	private String description;
	private boolean changedDescription = 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
	*/
	ProductBuilder()
	{
		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
	*/
	ProductBuilder(final IProduct 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.PRODUCT);
			return;
		}

		newInstance = false;
		oldInstance = oldVal;

		Product baseObj;
		if (oldVal instanceof Product)
		{
			baseObj = (Product)oldVal;
			this.id = baseObj.getId();
			this.productCategoryId = baseObj.getProductCategoryId();
			this.plantSpeciesId = baseObj.getPlantSpeciesId();
			this.plantVarietyId = baseObj.getPlantVarietyId();
			this.productBrandId = baseObj.getProductBrandId();
			this.name = baseObj.getName();
			this.nameDetail_1 = baseObj.getNameDetail_1().orElse(null);
			this.nameDetail_2 = baseObj.getNameDetail_2().orElse(null);
			this.description = baseObj.getDescription().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.getProductCategory();
			if (ky == null)
			{
				this.productCategoryId = 0;
			}
			else
			{
				this.productCategoryId = ((IProductCategory)ky).getKey();
			}
			ky = oldVal.getPlantSpecies().orElse(null);
			if (ky == null)
			{
				this.plantSpeciesId = null;
			}
			else
			{
				this.plantSpeciesId = ((IPlantSpecies)ky).getKey();
			}
			ky = oldVal.getPlantVariety().orElse(null);
			if (ky == null)
			{
				this.plantVarietyId = null;
			}
			else
			{
				this.plantVarietyId = ((IPlantVariety)ky).getKey();
			}
			ky = oldVal.getProductBrand().orElse(null);
			if (ky == null)
			{
				this.productBrandId = null;
			}
			else
			{
				this.productBrandId = ((IProductBrand)ky).getKey();
			}
			this.name = oldVal.getName();
			this.nameDetail_1 = oldVal.getNameDetail_1().orElse(null);
			this.nameDetail_2 = oldVal.getNameDetail_2().orElse(null);
			this.description = oldVal.getDescription().orElse(null);
			this.lastUpdated = oldVal.getLastUpdated();
			this.created = oldVal.getCreated();
		}
		commentHandler = new DBCommentHandler(NotebookEntryType.PRODUCT, this.id);
		LOGGER.traceExit();
	}	//	constructor()

	/**
	*	give the (new) value of productCategoryId
	*
	*	@param	newVal	the new value
	*	@return	this Builder
	*/
	IProductBuilder productCategoryId(final int newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("productCategoryId(): oldVal={}, newVal={}", this.productCategoryId, newVal);
		if (this.productCategoryId == newVal) return this;
		this.productCategoryId = newVal;
		changedProductCategoryId = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}
	@Override
	public IProductBuilder productCategory(final IProductCategory newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("productCategory(): oldVal={}, newVal={}", this.productCategoryId, newVal);
		if (newVal == null) return this;
		if (this.productCategoryId == newVal.getKey()) return this;
		this.productCategoryId = newVal.getKey();
		changedProductCategoryId = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}

	/**
	*	give the (new) value of plantSpeciesId
	*
	*	@param	newVal	the new value
	*	@return	this Builder
	*/
	IProductBuilder 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 IProductBuilder plantSpecies(final IPlantSpecies newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("plantSpecies(): oldVal={}, newVal={}", this.plantSpeciesId, newVal);
		if ((newVal == null) && (this.plantSpeciesId == null)) return this;
		if ((newVal != null) && (this.plantSpeciesId != null) && (this.plantSpeciesId.equals(newVal.getKey()))) return this;
		if (newVal == null)
		{
			this.plantSpeciesId = null;
			if (this.plantVarietyId != null)
			{
				this.plantVarietyId = null;
				changedPlantVarietyId = true;
			}
		}
		else
		{	//	non-null value
			this.plantSpeciesId = newVal.getKey();
			if (this.plantVarietyId != null)
			{
				this.plantVarietyId = null;
				changedPlantVarietyId = true;
			}
		}
		changedPlantSpeciesId = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}

	/**
	*	give the (new) value of plantVarietyId
	*
	*	@param	newVal	the new value
	*	@return	this Builder
	*/
	IProductBuilder 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 IProductBuilder 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
            LOGGER.debug("plantSpeciesId of NEW var: {}, spId currently: {}", ps_Id, this.plantSpeciesId);
			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;
	}

	/**
	*	give the (new) value of productBrandId
	*
	*	@param	newVal	the new value
	*	@return	this Builder
	*/
	IProductBuilder productBrandId(final int newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("productBrandId(): oldVal={}, newVal={}", this.productBrandId, newVal);
		if (this.productBrandId == newVal) return this;
		this.productBrandId = newVal;
		changedProductBrandId = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}
	@Override
	public IProductBuilder productBrand(final IProductBrand newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("productBrand(): oldVal={}, newVal={}", this.productBrandId, newVal);
		if ((newVal == null) && (this.productBrandId == null)) return this;
		if ((newVal != null) && (this.productBrandId != null) && (this.productBrandId.equals(newVal.getKey()))) return this;
		if (newVal == null)
		{
			this.productBrandId = null;
		}
		else
		{	//	non-null value
			this.productBrandId = newVal.getKey();
		}
		changedProductBrandId = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	@Override
	public IProductBuilder 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 IProductBuilder 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 IProductBuilder 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 IProduct 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.cacheProduct.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.cacheProduct.remove(this.id);
		}
// populate the cache
		new ProductLister().id(this.id).fetch();
		IProduct newValue = MySQLCache.cacheProduct.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.cacheProductCategory.get(productCategoryId).flagChildAdded(newValue);
			if (changedPlantSpeciesId && (plantSpeciesId != null) )
			{
				MySQLCache.cachePlantSpecies.get(plantSpeciesId).flagChildAdded(newValue);
			}
			if (changedPlantVarietyId && (plantVarietyId != null) )
			{
				MySQLCache.cachePlantVariety.get(plantVarietyId).flagChildAdded(newValue);
			}
			if (changedProductBrandId && (productBrandId != null) )
			{
				MySQLCache.cacheProductBrand.get(productBrandId).flagChildAdded(newValue);
			}
		}
		else
		{	//	updated
			if (changedProductCategoryId)
			{
				if (oldInstance != null)
				{
					MySQLCache.cacheProductCategory.get(oldInstance.getProductCategory().getKey()).flagChildDeleted(oldInstance);
				}
				MySQLCache.cacheProductCategory.get(newValue.getProductCategory().getKey()).flagChildAdded(newValue);
			}
			if (changedPlantSpeciesId)
			{
				if (oldInstance != null)
				{
					oldInstance.getPlantSpecies().ifPresent(item -> MySQLCache.cachePlantSpecies.get(item.getKey()).flagChildDeleted(oldInstance) );
				}
				newValue.getPlantSpecies().ifPresent(item -> MySQLCache.cachePlantSpecies.get(item.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) );
			}
			if (changedProductBrandId)
			{
				if (oldInstance != null)
				{
					oldInstance.getProductBrand().ifPresent(item -> MySQLCache.cacheProductBrand.get(item.getKey()).flagChildDeleted(oldInstance) );
				}
				newValue.getProductBrand().ifPresent(item -> MySQLCache.cacheProductBrand.get(item.getKey()).flagChildAdded(newValue) );
			}
		}

		//	stop multiple saves!
		oldInstance = null;

		somethingChanged = false;
		changedComments = false;
		changedAncestor = false;
		changedProductCategoryId = false;
		changedPlantSpeciesId = false;
		changedPlantVarietyId = false;
		changedProductBrandId = false;
		changedName = false;
		changedNameDetail_1 = false;
		changedNameDetail_2 = false;
		changedDescription = 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.productCategoryId <= 0)
		{
			LOGGER.debug("productCategoryId not set");
			return false;
		}
		if (this.name == null ||
			this.name.isEmpty() )
		{
			LOGGER.debug("name not set");
			return false;
		}
		return true;
	}	// canSave()

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

		if (newInstance) return LOGGER.traceExit(log4jEntryMsg, false);

		boolean  readValue = false;
		try (	Connection conn = DBConnection.getConnection();
				Statement stmt = conn.createStatement();	)
		{
            String query;
            ResultSet rs;

			switch (DBConnection.DB_IN_USE)
			{
				case MariaDB, MySQL -> query = "select exists (select 1 from purchaseitem where productId = " + this.id + ") as fred";
				case hsqldb -> query = "select exists (select 1 from purchaseitem where productId = " + this.id + ") as fred from (values(99))";
				case MSSQLServer -> query = "select CASE WHEN EXISTS (select 1 from purchaseitem where productId = " + this.id + ") THEN 1 ELSE 0 END as fred";
				default -> {
					LOGGER.error("canDelete(): no known rdbms");
					throw new GNDBException(new IllegalStateException("PurchaseBuilder: canDelete(): no known RDBMS"));
				}
			}
LOGGER.debug("canDelete(): query: {}", query);
			rs = stmt.executeQuery(query);
            rs.next();
            readValue = rs.getBoolean("fred");
            rs.close();
LOGGER.debug("canDelete(): readValue: {}", readValue);
			if (readValue)
			{
				return LOGGER.traceExit(log4jEntryMsg, false);
			}

			switch (DBConnection.DB_IN_USE)
			{
				case MariaDB, MySQL -> query = "select exists (select 1 from retailerhasproduct where productId = " + this.id + ") as fred";
				case hsqldb -> query = "select exists (select 1 from retailerhasproduct where productId = " + this.id + ") as fred from (values(99))";
				case MSSQLServer -> query = "select CASE WHEN EXISTS (select 1 from retailerhasproduct where productId = " + this.id + ") THEN 1 ELSE 0 END as fred";
				default -> {
					LOGGER.error("canDelete(): no known rdbms");
					throw new GNDBException(new IllegalStateException("PurchaseBuilder: canDelete(): no known RDBMS"));
				}
			}
LOGGER.debug("canDelete(): query: {}", query);
			rs = stmt.executeQuery(query);
            rs.next();
            readValue = rs.getBoolean("fred");
            rs.close();
LOGGER.debug("canDelete(): readValue: {}", readValue);
			if (readValue)
			{
				return LOGGER.traceExit(log4jEntryMsg, false);
			}

			switch (DBConnection.DB_IN_USE)
			{
				case MariaDB, MySQL -> query = "select exists (select 1 from shoppinglist where productId = " + this.id + ") as fred";
				case hsqldb -> query = "select exists (select 1 from shoppinglist where productId = " + this.id + ") as fred from (values(99))";
				case MSSQLServer -> query = "select CASE WHEN EXISTS (select 1 from shoppinglist where productId = " + this.id + ") THEN 1 ELSE 0 END as fred";
				default -> {
					LOGGER.error("canDelete(): no known rdbms");
					throw new GNDBException(new IllegalStateException("PurchaseBuilder: canDelete(): no known RDBMS"));
				}
			}
LOGGER.debug("canDelete(): query: {}", query);
			rs = stmt.executeQuery(query);
            rs.next();
            readValue = rs.getBoolean("fred");
            rs.close();
LOGGER.debug("canDelete(): readValue: {}", readValue);
			if (readValue)
			{
				return LOGGER.traceExit(log4jEntryMsg, false);
			}

			switch (DBConnection.DB_IN_USE)
			{
				case MariaDB, MySQL -> query = "select exists (select 1 from reviewreferences where productId = " + this.id + ") as fred";
				case hsqldb -> query = "select exists (select 1 from reviewreferences where productId = " + this.id + ") as fred from (values(99))";
				case MSSQLServer -> query = "select CASE WHEN EXISTS (select 1 from reviewreferences where productId = " + this.id + ") THEN 1 ELSE 0 END as fred";
				default -> {
					LOGGER.error("canDelete(): no known rdbms");
					throw new GNDBException(new IllegalStateException("PurchaseBuilder: canDelete(): no known RDBMS"));
				}
			}
			LOGGER.debug("canDelete(): query: {}", query);
			rs = stmt.executeQuery(query);
			rs.next();
			readValue = rs.getBoolean("fred");
			rs.close();
			LOGGER.debug("canDelete(): readValue: {}", readValue);
			if (readValue)
			{
				return LOGGER.traceExit(log4jEntryMsg, false);
			}
			stmt.close();
		}catch (SQLException ex) {
			LOGGER.error("canDelete(): SQLException: errorCode: {}, SQLstate: {}, message: {}", ex.getErrorCode(), ex.getSQLState(), ex.getMessage());
			throw new GNDBException(ex, ex.getErrorCode(), ex.getSQLState());
		}
		return LOGGER.traceExit(log4jEntryMsg, !readValue);
	}	// 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 product where productId = " + 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 = 'PR'";
				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.cacheProduct.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.cacheProductCategory.get(oldInstance.getProductCategory().getKey()).flagChildDeleted(oldInstance);
			oldInstance.getPlantSpecies().ifPresent(item -> MySQLCache.cachePlantSpecies.get(item.getKey()).flagChildDeleted(oldInstance) );
			oldInstance.getPlantVariety().ifPresent(item -> MySQLCache.cachePlantVariety.get(item.getKey()).flagChildDeleted(oldInstance) );
			oldInstance.getProductBrand().ifPresent(item -> MySQLCache.cacheProductBrand.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 product set ");
		if (changedProductCategoryId)
		{
			query.append("productCategoryId = ?, ");
		}

		if (changedPlantSpeciesId)
		{
			query.append("plantSpeciesId = ?, ");
		}

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

		if (changedProductBrandId)
		{
			query.append("productBrandId = ?, ");
		}

		if (changedName)
		{
			query.append("name = ?, ");
		}

		if (changedNameDetail_1)
		{
			query.append("nameDetail_1 = ?, ");
		}

		if (changedNameDetail_2)
		{
			query.append("nameDetail_2 = ?, ");
		}

		if (changedDescription)
		{
			query.append("description = ?, ");
		}

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

			if (changedPlantSpeciesId)
			{
				if (this.plantSpeciesId == null)
				{
LOGGER.debug("doUpdate(): param {} null", paramIx);
					stmt.setNull(paramIx++, java.sql.Types.INTEGER);
				}
				else
				{
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 (changedProductBrandId)
			{
				if (this.productBrandId == null)
				{
LOGGER.debug("doUpdate(): param {} null", paramIx);
					stmt.setNull(paramIx++, java.sql.Types.INTEGER);
				}
				else
				{
LOGGER.debug("doUpdate(): param {}={}", paramIx, this.productBrandId);
					stmt.setInt(paramIx++, this.productBrandId);
				}
			}

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

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

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

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

			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.changedProductCategoryId)
		{
			throw LOGGER.throwing(Level.ERROR, new IllegalStateException("ProductBuilder: doInsert(): productCategoryId unspecified"));
		}
		if (!this.changedName)
		{
			throw LOGGER.throwing(Level.ERROR, new IllegalStateException("ProductBuilder: doInsert(): name unspecified"));
		}

		StringBuilder query = new StringBuilder("insert into product (");
		query.append("productCategoryId, ");
		query.append("name, ");
		if (changedPlantSpeciesId)
		{
			query.append("plantSpeciesId, ");
		}

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

		if (changedProductBrandId)
		{
			query.append("productBrandId, ");
		}

		if (changedNameDetail_1)
		{
			query.append("nameDetail_1, ");
		}

		if (changedNameDetail_2)
		{
			query.append("nameDetail_2, ");
		}

		if (changedDescription)
		{
			query.append("description, ");
		}

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

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

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

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

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

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

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

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

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

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

			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 product (");
        query.append("productId, ");
		query.append("productCategoryId, ");
		query.append("plantSpeciesId, ");
		query.append("plantVarietyId, ");
		query.append("productBrandId, ");
		query.append("name, ");
		query.append("nameDetail_1, ");
		query.append("nameDetail_2, ");
		query.append("description, ");
		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("?, ");
		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);
            int txCount = 0;
            if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
            {
                conn.createStatement().execute("SET IDENTITY_INSERT product ON");
            }
            
            for (JsonObject jo : newVal)
            {
                if (!"DUMP".equals(jo.getString("JsonMode", "DUMP")))
                {
                    LOGGER.error("Product DUMP object is not DUMP");
                    throw new IllegalArgumentException("Product DUMP object is not DUMP");
                }
                if (!"Product".equals(jo.getString("JsonNBClass", "Product")))
                {
                    LOGGER.error("Product DUMP object is not Product");
                    throw new IllegalArgumentException("Product DUMP object is not Product");
                }
                Product ps = new Product(jo);
                if (ps.getId() <= 0)
                {//this forces the value of the id field.  The >0 test is a bodge.
                    LOGGER.error("Product DUMP object does not have an id");
                    throw new IllegalArgumentException("Product 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.getProductCategoryId());
                stmt.setInt(paramIx++, ps.getProductCategoryId());
                if (ps.getPlantSpeciesId() == null)
                {
LOGGER.debug("restoreJsonDump(): param {} null", paramIx);
                    stmt.setNull(paramIx++, java.sql.Types.INTEGER);
                }
                else
                {
LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getPlantSpeciesId());
                    stmt.setInt(paramIx++, ps.getPlantSpeciesId());
                }

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

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

LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getName());
                stmt.setString(paramIx++, ps.getName());
                
                if (!ps.getNameDetail_1().isPresent())
                {
LOGGER.debug("restoreJsonDump(): param {} null", paramIx);
                    stmt.setNull(paramIx++, java.sql.Types.VARCHAR);
                }
                else
                {
LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getNameDetail_1().get());
                    stmt.setString(paramIx++, ps.getNameDetail_1().get());
                }

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

                if (!ps.getDescription().isPresent())
                {
LOGGER.debug("restoreJsonDump(): param {} null", paramIx);
                    stmt.setNull(paramIx++, java.sql.Types.VARCHAR);
                }
                else
                {
LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getDescription().get());
                    stmt.setString(paramIx++, ps.getDescription().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 product OFF");
                    }
                    CommentBuilder cb = new CommentBuilder(NotebookEntryType.PRODUCT, ps.getId());
                    cb.doJsonInsert(ps.getComments(), conn);
                    if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
                    {
                        conn.createStatement().execute("SET IDENTITY_INSERT product ON");
                    }
                }

                if (++txCount > 50)
                {
                    conn.commit();
                    txCount = 0;
                }
            }
            if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
            {
                conn.createStatement().execute("SET IDENTITY_INSERT product OFF");
            }
            conn.commit();
		}catch (SQLException ex) {
			LOGGER.error("restoreJsonDump(): 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 IProductBuilder ancestor(IPurchaseItem ancestor) throws GNDBException
	{
		return this;
	}	//	ancestor(PurchaseItem)

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

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

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

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

}

