/*
 * Copyright (C) 2018-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.5   Guard against occasional NPE on item delete removing base listeners
    2.9.6	When a Diary entry is added/changed, make sure updated comments are shown
    3.0.0	Fix bug whereby ALL extant PlantNotes were added to a new PlantVariety
    3.0.4	Comment handling
    3.1.1	Add a method to just load all PVs
 */

package uk.co.gardennotebook.fxbean;

import javafx.beans.property.*;
import uk.co.gardennotebook.spi.*;
import uk.co.gardennotebook.util.StoryLineTree;
import java.util.Optional;
import java.util.List;
import java.beans.PropertyChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.beans.value.ChangeListener;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

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;

import java.time.*;

import javafx.beans.property.SimpleObjectProperty;

/**
	*	A particular variety of a plant species.<BR>
 *	  Note that the common name is NOT a unique value as different species may have varieties with the same name - e.g. Money Maker tomato AND aubergine.<BR>
 *
 *@apiNote
	*	Note the use of a Trigger to reflect changes to commonName into Product.
	*
	*	@author	Andy Gegg
	*	@version	3.1.1
	*	@since	1.0
*/
final public class PlantVarietyBean implements INotebookBean
{
	private static final Logger LOGGER = LogManager.getLogger();

	private IPlantVariety baseItem = null;

	private Integer itemKey = 0;
	private boolean newItem = false;
	private boolean explicitSave = false;
	private final SimpleBooleanProperty saveRequiredProperty = new SimpleBooleanProperty(this, "saveRequired", explicitSave);
	private IPlantVarietyBuilder explicitBuilder = null;

		// handle changes to the base item itself
	private PropertyChangeListener baseItemDeleted;
	private PropertyChangeListener baseItemReplaced;

	private final SimpleObjectProperty<PlantSpeciesBean> parentPlantSpeciesProperty = new SimpleObjectProperty<>(this, "plantSpecies", null);
	private final ChangeListener<PlantSpeciesBean> plantSpeciesIdListener = this::onPlantSpeciesIdChange;

	/*
	*	The usual name for this variety.
@apiNote
The values in this column are NOT unique
	*/
	private final SimpleStringProperty commonNameProperty = new SimpleStringProperty(this, "commonName", "");
	private final ChangeListener<String> commonNameListener = this::onCommonNameChange;

	/*
	*	The formal horticultural name for this variety.  Rarely different from the species' latin name.
	*/
	private final SimpleStringProperty latinNameProperty = new SimpleStringProperty(this, "latinName", "");
	private final ChangeListener<String> latinNameListener = this::onLatinNameChange;

	/*
	*	This implements the concept of synonyms.
*	All varieties which are synonyms of each other will have the same value for synonymSet which is a user chosen string.
*	A null value means the variety is NOT a synonym.
@apiNote
To get a PV and all its synonyms:
select p2.* from PV p1, PV p2 where p1.id in (...) and (p2.id = p1.id or p2.synonymSet = p1.synonymSet) and p1.PSid = p2.PSid
<BR>
this relies on the synonymSet being null if NOT in a synonymSet
<P>
Note that the choice of using a String value was pretty much forced on me by the need to be nullable.
*	The (unexpected) benefit is that the user can choose the value and maintenance just falls out of the generators.
*	I had to get past the idea that a PV is a synonym of some 'correct' PV - all names are equally valid!
	*/
	private final SimpleStringProperty synonymSetProperty = new SimpleStringProperty(this, "synonymSet", "");
	private final ChangeListener<String> synonymSetListener = this::onSynonymSetChange;

	private final SimpleStringProperty descriptionProperty = new SimpleStringProperty(this, "description", "");
	private final ChangeListener<String> descriptionListener = this::onDescriptionChange;

	/*
	*	The plant's function in the garden, typically vegetable, ornamental, weed.
	*/
	private final SimpleStringProperty utilityProperty = new SimpleStringProperty(this, "utility", "");
	private final ChangeListener<String> utilityListener = this::onUtilityChange;

	/*
	*	The plant's hardiness or tenderness, typically hardy, half hardy, tender.
	*/
	private final SimpleStringProperty hardinessProperty = new SimpleStringProperty(this, "hardiness", "");
	private final ChangeListener<String> hardinessListener = this::onHardinessChange;

	/*
	*	Typically annual, biennial or perennial.  Variations such as 'perennial grown as annual' (e.g. runner bean).
	*/
	private final SimpleStringProperty lifeTypeProperty = new SimpleStringProperty(this, "lifeType", "");
	private final ChangeListener<String> lifeTypeListener = this::onLifeTypeChange;

	/*
	*	Such as climber, shrub, tree.
	*/
	private final SimpleStringProperty plantTypeProperty = new SimpleStringProperty(this, "plantType", "");
	private final ChangeListener<String> plantTypeListener = this::onPlantTypeChange;

	private final ReadOnlyObjectWrapper<LocalDateTime> lastUpdatedProperty = new ReadOnlyObjectWrapper<>(this, "lastUpdated", LocalDateTime.now());
	private final ReadOnlyObjectWrapper<LocalDateTime> createdProperty = new ReadOnlyObjectWrapper<>(this, "created", LocalDateTime.now());
	private ReadOnlyBooleanWrapper canDeleteProperty = null;
	private final ReadOnlyBooleanWrapper hasAncestorProperty = new ReadOnlyBooleanWrapper(this, "hasAncestor", false);
	private final ReadOnlyBooleanWrapper hasDescendantProperty = new ReadOnlyBooleanWrapper(this, "hasDescendant", false);

	private ReadOnlyBooleanWrapper isNewProperty = new ReadOnlyBooleanWrapper(this, "isNew", newItem);	//	2.9.6

	private BeanCommentHandler<IPlantVariety> beanCommentHandler;	//	2.9.6
	private final ReadOnlyStringWrapper commentTextProperty = new ReadOnlyStringWrapper(this, "commentText", "");	//	2.9.6

	private ObservableList<AfflictionEventBean> childrenAfflictionEvent = null;
	private PropertyChangeListener baseItemAfflictionEventChanged;

	private ObservableList<GroundworkBean> childrenGroundwork = null;
	private PropertyChangeListener baseItemGroundworkChanged;

	private ObservableList<HusbandryBean> childrenHusbandry = null;
	private PropertyChangeListener baseItemHusbandryChanged;

	private ObservableList<PlantNoteBean> childrenPlantNote = null;
	private PropertyChangeListener baseItemPlantNoteChanged;

	private ObservableList<ProductBean> childrenProduct = null;
	private PropertyChangeListener baseItemProductChanged;

	private ObservableList<ReminderBean> childrenReminder = null;
	private PropertyChangeListener baseItemReminderChanged;

	private ObservableList<SaleItemBean> childrenSaleItem = null;
	private PropertyChangeListener baseItemSaleItemChanged;

	private ObservableList<ToDoListBean> childrenToDoList = null;
	private PropertyChangeListener baseItemToDoListChanged;

	private ObservableList<CroppingActualBean> childrenCroppingActual = null;
	private PropertyChangeListener baseItemCroppingActualChanged;

	/**
	*	Construct an 'empty' Bean.  Set the various property values then call save() to create the new PlantVarietyBean
	*/
	public PlantVarietyBean()
	{
		this(null);
	}
	/**
	*	Construct a Bean wrapping the given PlantVariety
	*	If the parameter is null a new 'empty' Bean will be constructed
	*
	*	@param	initialValue	the PlantVariety to wrap.  If null an 'empty' bean will be constructed
	*
	*/
	public PlantVarietyBean(final IPlantVariety initialValue)
	{
		ChangeListener<Boolean> saveRequiredListener = (obs, old, nval) -> {
			if (nval && !explicitSave)
			{
				explicitSave = true;
				ITrug server = TrugServer.getTrugServer().getTrug();
				explicitBuilder = server.getPlantVarietyBuilder(baseItem);
			}
			if (!nval && explicitSave && (baseItem != null))
			{
				explicitSave = false;
				explicitBuilder = null;
			}
		};

		saveRequiredProperty.addListener(saveRequiredListener);

		if(initialValue == null)
		{
			newItem = true;
			//	add the listeners BEFORE setting values, or default values never get sent to the builder!
			addListeners();
			setDefaults();
			saveRequiredProperty.set(true);
			return;
		}

		baseItem = initialValue;

		itemKey = baseItem.getKey();

		newItem = false;
		setValues();

		addListeners();
		declareBaseListeners();
		addBaseListeners();
	}

	/**
	*	Returns all PlantVariety items for a PlantSpecies wrapped as PlantVarietyBean.
	*
	*	@param	parent	the PlantSpecies whose Varieties are required
	*
	*	@return	a collection of PlantVarietyBean beans
	*
	*	@throws	GNDBException	if the underlying persisted storage engine (e.g. database server) throws an exception
	*				The original error can be retrieved by <code>getCause()</code>
	*/
	public static ObservableList<PlantVarietyBean> fetchAll(final PlantSpeciesBean parent) throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("fetchAll(): parent={}", parent);
		ITrug server = TrugServer.getTrugServer().getTrug();
		IPlantVarietyLister gal = server.getPlantVarietyLister().plantSpecies(parent.get().get());
		List<PlantVarietyBean> ll = gal.fetch().stream().map(PlantVarietyBean::new).toList();
		LOGGER.traceExit();
		return FXCollections.observableArrayList(ll);
	}

	/**
	 *	Loads all PlantVariety items.
	 *	Used in the initialisation phase to make sure PVs are available from the start for various
	 *	situations, e.g. going immediately to File| New | Husbandry or straight to the Plants tab.
	 *
	 *	@throws	GNDBException	if the underlying persisted storage engine (e.g. database server) throws an exception
	 *				The original error can be retrieved by <code>getCause()</code>
	 *
	 * @since 3.1.1
	 */
	public static  void forceLoad() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("forceLoad()");
		ITrug server = TrugServer.getTrugServer().getTrug();
		IPlantVarietyLister gal = server.getPlantVarietyLister();
		gal.fetch();
		LOGGER.traceExit();
		return;
	}

	/**
	*	Returns the underlying PlantVariety, if present
	*
	*	@return	the underlying PlantVariety, if present
	*/
	public Optional<IPlantVariety> get()
	{
		return getValue();
	}

	/**
	*	Returns the underlying PlantVariety if present
	*
	*	@return	the underlying PlantVariety, if present
	*/
	public Optional<IPlantVariety> getValue()
	{
		return Optional.ofNullable(baseItem);
	}

	@Override
	public NotebookEntryType getType()
	{
		return NotebookEntryType.PLANTVARIETY;
	}

	@Override
	public Integer getKey()
	{
		return itemKey;
	}

	@Override
	public boolean sameAs(final INotebookBean other)
	{
		if (other == null || ((PlantVarietyBean)other).baseItem == null || baseItem == null)
		{
			return false;
		}
		if (other.getType() != NotebookEntryType.PLANTVARIETY)
		{
			return false;
		}
		return baseItem.sameAs(((PlantVarietyBean)other).baseItem);
	}

	@Override
	public boolean isNew()
	{
		return isNewProperty().get();
	}

	@Override
	public ReadOnlyBooleanProperty isNewProperty()
	{
		if (isNewProperty == null)
		{
			isNewProperty = new ReadOnlyBooleanWrapper(this, "isNew", newItem);
		}
		return isNewProperty.getReadOnlyProperty();
	}

	@Override
	public boolean canDelete() throws GNDBException
	{
		return canDeleteProperty().get();
	}

	@Override
	public ReadOnlyBooleanProperty canDeleteProperty() throws GNDBException
	{
		if (canDeleteProperty == null)
		{
			ITrug server = TrugServer.getTrugServer().getTrug();
			boolean canDel = server.getPlantVarietyBuilder(baseItem).canDelete();
			canDeleteProperty = new ReadOnlyBooleanWrapper(this, "canDelete", canDel);
		}
		return canDeleteProperty.getReadOnlyProperty();
	}

	@Override
	public boolean hasAncestor() throws GNDBException
	{
		//	PlantVariety items do not participate in story lines
		return false;
	}

	@Override
	public ReadOnlyBooleanProperty hasAncestorProperty() throws GNDBException
	{
		//	PlantVariety items do not participate in story lines
		return hasAncestorProperty.getReadOnlyProperty();
	}	//	hasAncestorProperty()

	@Override
	public StoryLineTree<? extends INotebookBean> getAncestors() throws GNDBException
	{
		//	PlantVariety items do not participate in story lines
			return StoryLineTree.emptyTree();
	}	//	getAncestors()

	@Override
	public boolean hasDescendant() throws GNDBException
	{
		//	PlantVariety items do not participate in story lines
		return false;
	}

	@Override
	public ReadOnlyBooleanProperty hasDescendantProperty() throws GNDBException
	{
		//	PlantVariety items do not participate in story lines
		return hasDescendantProperty.getReadOnlyProperty();
	}	//	hasDescendantProperty()

	@Override
	public StoryLineTree<? extends INotebookBean> getDescendants() throws GNDBException
	{
		//	PlantVariety items do not participate in story lines
			return StoryLineTree.emptyTree();
	}	//	getDescendants()

	public PlantSpeciesBean getPlantSpecies()
	{
		return plantSpeciesProperty().getValue();
	}
	public void setPlantSpecies(final PlantSpeciesBean bean)
	{
		plantSpeciesProperty().setValue(bean);
	}
	public void setPlantSpecies(final IPlantSpecies item)
	{
		plantSpeciesProperty().setValue(new PlantSpeciesBean(item));
	}
	/**
	*	Returns the PlantSpecies parent of the PlantVariety this Bean wraps
	*
	*	@return	the PlantSpecies parent of the PlantVariety this Bean wraps
	*/
	public ObjectProperty<PlantSpeciesBean> plantSpeciesProperty()
	{
		return parentPlantSpeciesProperty;
	}

	/**
	*	Handle changes to the PlantSpeciesId value
	*
	*	@throws	GNDBRuntimeException	if the underlying persisted storage engine (e.g. database server) throws an exception
	*				The original error can be retrieved by <code>getCause()</code>
	*/
	private void onPlantSpeciesIdChange(ObservableValue<? extends PlantSpeciesBean> obs, PlantSpeciesBean old, PlantSpeciesBean nval)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("onPlantSpeciesIdChange(): old={}, new={}", old, nval);
		if (nval == null)
		{	// this is an error condition and should be flagged
LOGGER.debug("onPlantSpeciesIdChange(): nval is null");
			return;
		}
		if (nval.sameAs(old))
		{
LOGGER.debug("onPlantSpeciesIdChange(): nval is sameAs old");
			return;
		}
		if (!nval.isNew())
		{
			if (explicitSave)
			{
				explicitBuilder.plantSpecies(nval.get().get());
			}
			else
			{
LOGGER.debug("onPlantSpeciesIdChange(): NOT explicitSave");
				ITrug server = TrugServer.getTrugServer().getTrug();
				//	the Builder will send an event to the baseItem to say it's been replaced
			try
			{
				server.getPlantVarietyBuilder(baseItem).plantSpecies(nval.get().get()).save();
			} catch (GNDBException ex) {
				throw new GNDBRuntimeException(ex);
			}
			}
		}

		LOGGER.traceExit(log4jEntryMsg);
	}


	public String getCommonName()
	{
		return commonNameProperty.get();
	}
	public void setCommonName(final String newVal)
	{
		commonNameProperty.set(newVal);
	}
	/**
	*	Wraps the CommonName value of the PlantVariety
	*
	*	@return	a writable property wrapping the commonName attribute
	*/
	public StringProperty commonNameProperty()
	{
		return commonNameProperty;
	}

	private void onCommonNameChange(ObservableValue<? extends String> obs, String old, String nval)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("onCommonNameChange(): old={}, new={}", old, nval);
		if (explicitSave)
		{
LOGGER.debug("onCommonNameChange(): explicitSave");
			explicitBuilder.commonName(nval);
		}
		else
		{
LOGGER.debug("onCommonNameChange(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			try
			{
				baseItem = server.getPlantVarietyBuilder(baseItem).commonName(nval).save();
			} catch (GNDBException ex) {
				throw new GNDBRuntimeException(ex);
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
	}

	public String getLatinName()
	{
		return latinNameProperty.get();
	}
	public void setLatinName(final String newVal)
	{
		latinNameProperty.set(newVal);
	}
	/**
	*	Wraps the LatinName value of the PlantVariety
	*
	*	@return	a writable property wrapping the latinName attribute
	*/
	public StringProperty latinNameProperty()
	{
		return latinNameProperty;
	}

	private void onLatinNameChange(ObservableValue<? extends String> obs, String old, String nval)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("onLatinNameChange(): old={}, new={}", old, nval);
		if (explicitSave)
		{
LOGGER.debug("onLatinNameChange(): explicitSave");
			explicitBuilder.latinName(nval);
		}
		else
		{
LOGGER.debug("onLatinNameChange(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			try
			{
				baseItem = server.getPlantVarietyBuilder(baseItem).latinName(nval).save();
			} catch (GNDBException ex) {
				throw new GNDBRuntimeException(ex);
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
	}

	public String getSynonymSet()
	{
		return synonymSetProperty.get();
	}
	public void setSynonymSet(final String newVal)
	{
		synonymSetProperty.set(newVal);
	}
	/**
	*	Wraps the SynonymSet value of the PlantVariety
	*
	*	@return	a writable property wrapping the synonymSet attribute
	*/
	public StringProperty synonymSetProperty()
	{
		return synonymSetProperty;
	}

	private void onSynonymSetChange(ObservableValue<? extends String> obs, String old, String nval)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("onSynonymSetChange(): old={}, new={}", old, nval);
		if (explicitSave)
		{
LOGGER.debug("onSynonymSetChange(): explicitSave");
			explicitBuilder.synonymSet(nval);
		}
		else
		{
LOGGER.debug("onSynonymSetChange(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			try
			{
				baseItem = server.getPlantVarietyBuilder(baseItem).synonymSet(nval).save();
			} catch (GNDBException ex) {
				throw new GNDBRuntimeException(ex);
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
	}

	public String getDescription()
	{
		return descriptionProperty.get();
	}
	public void setDescription(final String newVal)
	{
		descriptionProperty.set(newVal);
	}
	/**
	*	Wraps the Description value of the PlantVariety
	*
	*	@return	a writable property wrapping the description attribute
	*/
	public StringProperty descriptionProperty()
	{
		return descriptionProperty;
	}

	private void onDescriptionChange(ObservableValue<? extends String> obs, String old, String nval)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("onDescriptionChange(): old={}, new={}", old, nval);
		if (explicitSave)
		{
LOGGER.debug("onDescriptionChange(): explicitSave");
			explicitBuilder.description(nval);
		}
		else
		{
LOGGER.debug("onDescriptionChange(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			try
			{
				baseItem = server.getPlantVarietyBuilder(baseItem).description(nval).save();
			} catch (GNDBException ex) {
				throw new GNDBRuntimeException(ex);
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
	}

	public String getUtility()
	{
		return utilityProperty.get();
	}
	public void setUtility(final String newVal)
	{
		utilityProperty.set(newVal);
	}
	/**
	*	Wraps the Utility value of the PlantVariety
	*
	*	@return	a writable property wrapping the utility attribute
	*/
	public StringProperty utilityProperty()
	{
		return utilityProperty;
	}

	private void onUtilityChange(ObservableValue<? extends String> obs, String old, String nval)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("onUtilityChange(): old={}, new={}", old, nval);
		if (explicitSave)
		{
LOGGER.debug("onUtilityChange(): explicitSave");
			explicitBuilder.utility(nval);
		}
		else
		{
LOGGER.debug("onUtilityChange(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			try
			{
				baseItem = server.getPlantVarietyBuilder(baseItem).utility(nval).save();
			} catch (GNDBException ex) {
				throw new GNDBRuntimeException(ex);
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
	}

	public String getHardiness()
	{
		return hardinessProperty.get();
	}
	public void setHardiness(final String newVal)
	{
		hardinessProperty.set(newVal);
	}
	/**
	*	Wraps the Hardiness value of the PlantVariety
	*
	*	@return	a writable property wrapping the hardiness attribute
	*/
	public StringProperty hardinessProperty()
	{
		return hardinessProperty;
	}

	private void onHardinessChange(ObservableValue<? extends String> obs, String old, String nval)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("onHardinessChange(): old={}, new={}", old, nval);
		if (explicitSave)
		{
LOGGER.debug("onHardinessChange(): explicitSave");
			explicitBuilder.hardiness(nval);
		}
		else
		{
LOGGER.debug("onHardinessChange(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			try
			{
				baseItem = server.getPlantVarietyBuilder(baseItem).hardiness(nval).save();
			} catch (GNDBException ex) {
				throw new GNDBRuntimeException(ex);
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
	}

	public String getLifeType()
	{
		return lifeTypeProperty.get();
	}
	public void setLifeType(final String newVal)
	{
		lifeTypeProperty.set(newVal);
	}
	/**
	*	Wraps the LifeType value of the PlantVariety
	*
	*	@return	a writable property wrapping the lifeType attribute
	*/
	public StringProperty lifeTypeProperty()
	{
		return lifeTypeProperty;
	}

	private void onLifeTypeChange(ObservableValue<? extends String> obs, String old, String nval)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("onLifeTypeChange(): old={}, new={}", old, nval);
		if (explicitSave)
		{
LOGGER.debug("onLifeTypeChange(): explicitSave");
			explicitBuilder.lifeType(nval);
		}
		else
		{
LOGGER.debug("onLifeTypeChange(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			try
			{
				baseItem = server.getPlantVarietyBuilder(baseItem).lifeType(nval).save();
			} catch (GNDBException ex) {
				throw new GNDBRuntimeException(ex);
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
	}

	public String getPlantType()
	{
		return plantTypeProperty.get();
	}
	public void setPlantType(final String newVal)
	{
		plantTypeProperty.set(newVal);
	}
	/**
	*	Wraps the PlantType value of the PlantVariety
	*
	*	@return	a writable property wrapping the plantType attribute
	*/
	public StringProperty plantTypeProperty()
	{
		return plantTypeProperty;
	}

	private void onPlantTypeChange(ObservableValue<? extends String> obs, String old, String nval)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("onPlantTypeChange(): old={}, new={}", old, nval);
		if (explicitSave)
		{
LOGGER.debug("onPlantTypeChange(): explicitSave");
			explicitBuilder.plantType(nval);
		}
		else
		{
LOGGER.debug("onPlantTypeChange(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			try
			{
				baseItem = server.getPlantVarietyBuilder(baseItem).plantType(nval).save();
			} catch (GNDBException ex) {
				throw new GNDBRuntimeException(ex);
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
	}

	public LocalDateTime getLastUpdated()
	{
		return lastUpdatedProperty.get();
	}
	/**
	*	Wraps the LastUpdated value of the PlantVariety
	*	Note that this value cannot be changed by the user
	*
	*	@return	a read-only property wrapping the lastUpdated attribute
	*/
	public ReadOnlyObjectProperty<LocalDateTime> lastUpdatedProperty()
	{
		return lastUpdatedProperty.getReadOnlyProperty();
	}

	public LocalDateTime getCreated()
	{
		return createdProperty.get();
	}
	/**
	*	Wraps the Created value of the PlantVariety
	*	Note that this value cannot be changed by the user
	*
	*	@return	a read-only property wrapping the created attribute
	*/
	public ReadOnlyObjectProperty<LocalDateTime> createdProperty()
	{
		return createdProperty.getReadOnlyProperty();
	}

	/**
	*	Return a list of any AfflictionEvent of this PlantVariety or an empty list
	*
	*	@return	A list of AfflictionEvent items, possibly empty
	*
	*	@throws	GNDBException	if the underlying persisted storage engine (e.g. database server) throws an exception
	*				The original error can be retrieved by <code>getCause()</code>
	*/
	public ObservableList<AfflictionEventBean> getAfflictionEvent() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("getAfflictionEvent()");
		if (childrenAfflictionEvent == null)
		{
			childrenAfflictionEvent = FXCollections.observableArrayList();
			ITrug server = TrugServer.getTrugServer().getTrug();
			for (IAfflictionEvent ix : server.getAfflictionEventLister().plantVariety(baseItem).fetch())
			{
				childrenAfflictionEvent.add(new AfflictionEventBean(ix));
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
		return childrenAfflictionEvent;
	}

	/**
	*	Return a list of any Groundwork of this PlantVariety or an empty list
	*
	*	@return	A list of Groundwork items, possibly empty
	*
	*	@throws	GNDBException	if the underlying persisted storage engine (e.g. database server) throws an exception
	*				The original error can be retrieved by <code>getCause()</code>
	*/
	public ObservableList<GroundworkBean> getGroundwork() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("getGroundwork()");
		if (childrenGroundwork == null)
		{
			childrenGroundwork = FXCollections.observableArrayList();
			ITrug server = TrugServer.getTrugServer().getTrug();
			for (IGroundwork ix : server.getGroundworkLister().plantVariety(baseItem).fetch())
			{
				childrenGroundwork.add(new GroundworkBean(ix));
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
		return childrenGroundwork;
	}

	/**
	*	Return a list of any Husbandry of this PlantVariety or an empty list
	*
	*	@return	A list of Husbandry items, possibly empty
	*
	*	@throws	GNDBException	if the underlying persisted storage engine (e.g. database server) throws an exception
	*				The original error can be retrieved by <code>getCause()</code>
	*/
	public ObservableList<HusbandryBean> getHusbandry() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("getHusbandry()");
		if (childrenHusbandry == null)
		{
			childrenHusbandry = FXCollections.observableArrayList();
			ITrug server = TrugServer.getTrugServer().getTrug();
			for (IHusbandry ix : server.getHusbandryLister().plantVariety(baseItem).fetch())
			{
				childrenHusbandry.add(new HusbandryBean(ix));
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
		return childrenHusbandry;
	}

	/**
	*	Return a list of any PlantNote of this PlantVariety or an empty list
	*
	*	@return	A list of PlantNote items, possibly empty
	*
	*	@throws	GNDBException	if the underlying persisted storage engine (e.g. database server) throws an exception
	*				The original error can be retrieved by <code>getCause()</code>
	*/
	public ObservableList<PlantNoteBean> getPlantNote() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("getPlantNote()");
		if (childrenPlantNote == null)
		{
			childrenPlantNote = FXCollections.observableArrayList();
			if (baseItem != null)
			{
				ITrug server = TrugServer.getTrugServer().getTrug();
				for (IPlantNote ix : server.getPlantNoteLister().plantVariety(baseItem).fetch())
				{
					childrenPlantNote.add(new PlantNoteBean(ix));
				}
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
		return childrenPlantNote;
	}

	/**
	*	Return a list of any Product of this PlantVariety or an empty list
	*
	*	@return	A list of Product items, possibly empty
	*
	*	@throws	GNDBException	if the underlying persisted storage engine (e.g. database server) throws an exception
	*				The original error can be retrieved by <code>getCause()</code>
	*/
	public ObservableList<ProductBean> getProduct() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("getProduct()");
		if (childrenProduct == null)
		{
			childrenProduct = FXCollections.observableArrayList();
			ITrug server = TrugServer.getTrugServer().getTrug();
			for (IProduct ix : server.getProductLister().plantVariety(baseItem).fetch())
			{
				childrenProduct.add(new ProductBean(ix));
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
		return childrenProduct;
	}

	/**
	*	Return a list of any Reminder of this PlantVariety or an empty list
	*
	*	@return	A list of Reminder items, possibly empty
	*
	*	@throws	GNDBException	if the underlying persisted storage engine (e.g. database server) throws an exception
	*				The original error can be retrieved by <code>getCause()</code>
	*/
	public ObservableList<ReminderBean> getReminder() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("getReminder()");
		if (childrenReminder == null)
		{
			childrenReminder = FXCollections.observableArrayList();
			ITrug server = TrugServer.getTrugServer().getTrug();
			for (IReminder ix : server.getReminderLister().plantVariety(baseItem).fetch())
			{
				childrenReminder.add(new ReminderBean(ix));
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
		return childrenReminder;
	}

	/**
	*	Return a list of any SaleItem of this PlantVariety or an empty list
	*
	*	@return	A list of SaleItem items, possibly empty
	*
	*	@throws	GNDBException	if the underlying persisted storage engine (e.g. database server) throws an exception
	*				The original error can be retrieved by <code>getCause()</code>
	*/
	public ObservableList<SaleItemBean> getSaleItem() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("getSaleItem()");
		if (childrenSaleItem == null)
		{
			childrenSaleItem = FXCollections.observableArrayList();
			ITrug server = TrugServer.getTrugServer().getTrug();
			for (ISaleItem ix : server.getSaleItemLister().plantVariety(baseItem).fetch())
			{
				childrenSaleItem.add(new SaleItemBean(ix));
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
		return childrenSaleItem;
	}

	/**
	*	Return a list of any ToDoList of this PlantVariety or an empty list
	*
	*	@return	A list of ToDoList items, possibly empty
	*
	*	@throws	GNDBException	if the underlying persisted storage engine (e.g. database server) throws an exception
	*				The original error can be retrieved by <code>getCause()</code>
	*/
	public ObservableList<ToDoListBean> getToDoList() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("getToDoList()");
		if (childrenToDoList == null)
		{
			childrenToDoList = FXCollections.observableArrayList();
			ITrug server = TrugServer.getTrugServer().getTrug();
			for (IToDoList ix : server.getToDoListLister().plantVariety(baseItem).fetch())
			{
				childrenToDoList.add(new ToDoListBean(ix));
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
		return childrenToDoList;
	}

	/**
	 *	Return a list of any Reviews of this PlantVariety or an empty list
	 *
	 *	@return	A list of Review items, possibly empty
	 *
	 *	@throws	GNDBException	if the underlying persisted storage engine (e.g. database server) throws an exception
	 *				The original error can be retrieved by <code>getCause()</code>
	 */
	public ObservableList<ReviewBean> getReview() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("getReview()");
		//	TODO	get list of Reviews naming this PlantVariety
//		if (childrenToDoList == null)
//		{
//			childrenToDoList = FXCollections.observableArrayList();
//			ITrug server = TrugServer.getTrugServer().getTrug();
//			for (IToDoList ix : server.getToDoListLister().plantSpecies(baseItem).fetch())
//			{
//				childrenToDoList.add(new ToDoListBean(ix));
//			}
//		}
		LOGGER.traceExit(log4jEntryMsg);
		return FXCollections.emptyObservableList();
	}

	/**
	 *	Return a list of any CroppingActual items of this PlantVariety or an empty list
	 *
	 *	@return	A list of CroppingActual items, possibly empty
	 *
	 *	@throws	GNDBException	if the underlying persisted storage engine (e.g. database server) throws an exception
	 *				The original error can be retrieved by <code>getCause()</code>
	 */
	public ObservableList<CroppingActualBean> getCroppingActual() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("getCroppingActual()");
		if (childrenCroppingActual == null)
		{
			childrenCroppingActual = FXCollections.observableArrayList();
			ITrug server = TrugServer.getTrugServer().getTrug();
			for (ICroppingActual ix : server.getCroppingActualLister().plantVariety(baseItem).fetch())
			{
				childrenCroppingActual.add(new CroppingActualBean(ix));
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
		return childrenCroppingActual;
	}

	@Override
	public ObservableList<CommentBean> getComments()
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("getComments()");

		return LOGGER.traceExit(log4jEntryMsg, beanCommentHandler.getComments());
	}	//	getComments()

	//	2.9.6
	@Override
	public ReadOnlyStringProperty commentTextProperty()
	{
//		return beanCommentHandler.commentTextProperty();
		commentTextProperty.set(beanCommentHandler.commentTextProperty().get());
		return commentTextProperty;
	}

	@Override
	public void addComment(final String text) throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("addComment({})", text);
		if (text == null || text.isBlank()) return;	//	2.9.6

		beanCommentHandler.addComment(text);	//	2.9.6

		if (explicitSave)
		{
LOGGER.debug("addComment(): explicitSave");
		}
		else
		{	//	this cannot be a new instance of the parent PlantVariety
LOGGER.debug("addComment(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			baseItem = server.getPlantVarietyBuilder(baseItem).addComment(text).save();
			setValues();	//	2.9.6
		}
		LOGGER.traceExit(log4jEntryMsg);
	}	//	addComment()

	//	2.9.6
	@Override
	public void addComment(CommentBean comment) throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("addComment(comment bean): comment: {}, text : {}", comment, comment==null ? "null" :comment.getComment());
		if (comment == null) return;
		if (comment.getParentType() != this.getType()) return;
		if (comment.getComment() == null || comment.getComment().isBlank()) return;

		beanCommentHandler.addComment(comment);

		if (explicitSave)
		{
			LOGGER.debug("addComment(): explicitSave");
		}
		else
		{	//	this cannot be a new instance of the parent Wildlife
			LOGGER.debug("addComment(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			baseItem = server.getPlantVarietyBuilder(baseItem).addComment(comment.getComment()).save();
			setValues();	//	2.9.6
		}
		LOGGER.debug("addComment(comment bean): commentTextProperty: {}", commentTextProperty().get());

		LOGGER.traceExit(log4jEntryMsg);
	}

	@Override
	public void changeCommentText(final CommentBean comment, final String text) throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("changeCommentText(): comment={}, text={}", comment, text);
		if (text == null || text.isBlank()) return;

		if (comment == null)	//	2.9.6
		{
			addComment(text);
			return;
		}

		if (comment.getParentType() != this.getType()) return;

		beanCommentHandler.changeCommentText(comment, text);

		if (explicitSave)
		{
LOGGER.debug("changeCommentText(): explicitSave");
		}
		else
		{	//	this cannot be a new instance of the parent PlantVariety
LOGGER.debug("changeCommentText(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			baseItem = server.getPlantVarietyBuilder(baseItem).changeComment(comment.get().get(), text).save();
			setValues();	//	2.9.6
		}
		LOGGER.traceExit(log4jEntryMsg);
	}	//	changeCommentText()

	@Override
	public void changeCommentDate(CommentBean comment, final LocalDate date) throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("changeCommentDate(): comment={}, date={}", comment, date);
		if (date == null) return;

		//	2.9.6
		if (comment == null)
		{
			return;
		}

		if (comment.getParentType() != this.getType()) return;

		beanCommentHandler.changeCommentDate(comment, date);

		if (explicitSave)
		{
LOGGER.debug("changeCommentDate(): explicitSave");
		}
		else
		{	//	this cannot be a new instance of the parent PlantVariety
LOGGER.debug("changeCommentDate(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			baseItem = server.getPlantVarietyBuilder(baseItem).changeComment(comment.get().get(), date).save();
			setValues();	//	2.9.6
		}
		LOGGER.traceExit(log4jEntryMsg);
	}	//	changeCommentDate()

	@Override
	public void deleteComment(CommentBean comment) throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("deleteComment(): comment={}", comment);
		if (comment == null) return;

		if (comment.getParentType() != this.getType()) return;

		beanCommentHandler.deleteComment(comment);

		if (explicitSave)
		{
LOGGER.debug("deleteComment(): explicitSave");
		}
		else
		{	//	this cannot be a new instance of the parent PlantVariety
LOGGER.debug("deleteComment(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			baseItem = server.getPlantVarietyBuilder(baseItem).deleteComment(comment.get().get()).save();
			setValues();	//	2.9.6
		}
		LOGGER.traceExit(log4jEntryMsg);
	}	//	deleteComment()

	public boolean isSaveRequired()
	{
		return explicitSave;
	}
	public void setSaveRequired(boolean reqd)
	{
		saveRequiredProperty.set(reqd);
	}
	public BooleanProperty saveRequiredProperty()
	{
		return saveRequiredProperty;
	}

	public boolean needSave()
	{
		if (!explicitSave)
			return false;

		return explicitBuilder.needSave() || beanCommentHandler.needSave();
	}

	public boolean canSave()
	{
		if (!explicitSave)
			return true;

		return explicitBuilder.canSave();
	}

	/**
	*	Save changes to the underlying PlantVariety item
	*
	*	@throws	GNDBException	if the underlying persisted storage engine (e.g. database server) throws an exception
	*				The original error can be retrieved by <code>getCause()</code>
	*/
	public void save() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("save()");
		if (!explicitSave) return;

		saveComments();	//	2.9.6 - do this here so that explicitBuilder knows there's a change

		if (!explicitBuilder.needSave())
		{
			return;
		}
		if (!explicitBuilder.canSave())
		{
			throw new IllegalStateException("PlantVarietyBean: cannot save at this time - mandatory values not set");
		}

		baseItem = explicitBuilder.save();
		LOGGER.debug("save(): after explicitBuilder.save(): comments: {}", baseItem.getComments());	//	2.9.6
		setValues();	//	2.9.6
		saveRequiredProperty.set(false);
		LOGGER.traceExit(log4jEntryMsg);
	}	//	save()

	//	2.9.6
	private void saveComments()
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("saveComments()");

		beanCommentHandler.saveComments(
				cb -> explicitBuilder.addComment(cb.getComment()),	//	add
				cb -> explicitBuilder.changeComment(cb.get().get(), cb.getComment()),	//	change text
				cb -> explicitBuilder.changeComment(cb.get().get(), cb.getDate()),	//	change date
				cb -> explicitBuilder.deleteComment(cb.get().get())		//	delete
		);
	}

	/**
	*	Delete the underlying PlantVariety item
	*
	*	@throws	GNDBException	if the underlying persisted storage engine (e.g. database server) throws an exception
	*				The original error can be retrieved by <code>getCause()</code>
	*/
	public void delete() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("delete()");
		if (newItem) return;

		if (explicitSave)
		{
			explicitBuilder.delete();
			saveRequiredProperty.set(false);
		}
		else
		{
			ITrug server = TrugServer.getTrugServer().getTrug();
			server.getPlantVarietyBuilder(baseItem).delete();
		}
	}	//	delete()

	public void cancelEdit()
	{
		if (!explicitSave) return;
		if (newItem) return;

		saveRequiredProperty.set(false);
		setValues();
	}

	private void setDefaults()
	{
		saveRequiredProperty.setValue(false);
		commonNameProperty.setValue("");
		latinNameProperty.setValue("");
		synonymSetProperty.setValue("");
		descriptionProperty.setValue("");
		utilityProperty.setValue("");
		hardinessProperty.setValue("");
		lifeTypeProperty.setValue("");
		plantTypeProperty.setValue("");
		lastUpdatedProperty.setValue(LocalDateTime.now());
		createdProperty.setValue(LocalDateTime.now());
		childrenAfflictionEvent = null;
		baseItemAfflictionEventChanged = null;
		childrenGroundwork = null;
		baseItemGroundworkChanged = null;
		childrenHusbandry = null;
		baseItemHusbandryChanged = null;
		childrenPlantNote = null;
		baseItemPlantNoteChanged = null;
		childrenProduct = null;
		baseItemProductChanged = null;
		childrenReminder = null;
		baseItemReminderChanged = null;
		childrenSaleItem = null;
		baseItemSaleItemChanged = null;
		childrenToDoList = null;
		baseItemToDoListChanged = null;

		//	2.9.6
		isNewProperty.set(true);
		beanCommentHandler = new BeanCommentHandler<>(this, baseItem);
		commentTextProperty.set(beanCommentHandler.commentTextProperty().get());
	}

	private void setValues()
	{
		saveRequiredProperty.setValue(false);
		parentPlantSpeciesProperty.setValue(new PlantSpeciesBean(baseItem.getPlantSpecies()));
		commonNameProperty.setValue(baseItem.getCommonName());
		latinNameProperty.setValue(baseItem.getLatinName().orElse(""));
		synonymSetProperty.setValue(baseItem.getSynonymSet().orElse(""));
		descriptionProperty.setValue(baseItem.getDescription().orElse(""));
		utilityProperty.setValue(baseItem.getUtility().orElse(""));
		hardinessProperty.setValue(baseItem.getHardiness().orElse(""));
		lifeTypeProperty.setValue(baseItem.getLifeType().orElse(""));
		plantTypeProperty.setValue(baseItem.getPlantType().orElse(""));
		lastUpdatedProperty.setValue(baseItem.getLastUpdated());
		createdProperty.setValue(baseItem.getCreated());

		itemKey = baseItem.getKey();
		newItem = false;
		isNewProperty.set(false);	//	2.9.6

		LOGGER.debug("setvalues(): about to change BeanCommentHandler");
		beanCommentHandler = new BeanCommentHandler<>(this, baseItem);
		commentTextProperty.set(beanCommentHandler.commentTextProperty().get());
	}

	private void addListeners()
	{
		parentPlantSpeciesProperty.addListener(plantSpeciesIdListener);
		commonNameProperty.addListener(commonNameListener);
		latinNameProperty.addListener(latinNameListener);
		synonymSetProperty.addListener(synonymSetListener);
		descriptionProperty.addListener(descriptionListener);
		utilityProperty.addListener(utilityListener);
		hardinessProperty.addListener(hardinessListener);
		lifeTypeProperty.addListener(lifeTypeListener);
		plantTypeProperty.addListener(plantTypeListener);
	}
	private void removeListeners()
	{
		parentPlantSpeciesProperty.removeListener(plantSpeciesIdListener);
		commonNameProperty.removeListener(commonNameListener);
		latinNameProperty.removeListener(latinNameListener);
		synonymSetProperty.removeListener(synonymSetListener);
		descriptionProperty.removeListener(descriptionListener);
		utilityProperty.removeListener(utilityListener);
		hardinessProperty.removeListener(hardinessListener);
		lifeTypeProperty.removeListener(lifeTypeListener);
		plantTypeProperty.removeListener(plantTypeListener);
	}
	private void declareBaseListeners()
	{
		// handle changes to the base item itself
		baseItemDeleted = evt -> {
				removeListeners();
				removeBaseListeners();
				setDefaults();
				baseItem = null;
			};
		baseItemReplaced = evt -> {
				if (evt.getNewValue() != null)
				{
					removeBaseListeners();
					baseItem = (IPlantVariety)(evt.getNewValue());
					setValues();
					addBaseListeners();
				}
			};

		baseItemAfflictionEventChanged = evt -> {
				if (childrenAfflictionEvent == null)
				{
					return;
				}
				if (evt.getNewValue() != null)
				{
					if (!(evt.getNewValue() instanceof IAfflictionEvent))
					{
						throw new IllegalArgumentException("baseItemAfflictionEventChanged: newVal wrong type");
					}
					childrenAfflictionEvent.add(new AfflictionEventBean((IAfflictionEvent)(evt.getNewValue())));
				}
				else if (evt.getOldValue() != null)
				{
					if (!(evt.getOldValue() instanceof IAfflictionEvent))
					{
						throw new IllegalArgumentException("baseItemAfflictionEventChanged: oldVal wrong type");
					}
					//	When the db item is deleted it fires an event which is picked up here AND in the child bean
					//	The child bean sets its underlying baseItem to null so getValue() returns an Optional of null
					//	The order in which the event handlers are called is unpredictable
					childrenAfflictionEvent.removeIf(pr -> (pr.getValue().isEmpty()) ||
						(pr.getValue().
							get().
							getKey().
							equals(((IAfflictionEvent)(evt.getOldValue())).getKey())));
				}
			};

		baseItemGroundworkChanged = evt -> {
				if (childrenGroundwork == null)
				{
					return;
				}
				if (evt.getNewValue() != null)
				{
					if (!(evt.getNewValue() instanceof IGroundwork))
					{
						throw new IllegalArgumentException("baseItemGroundworkChanged: newVal wrong type");
					}
					childrenGroundwork.add(new GroundworkBean((IGroundwork)(evt.getNewValue())));
				}
				else if (evt.getOldValue() != null)
				{
					if (!(evt.getOldValue() instanceof IGroundwork))
					{
						throw new IllegalArgumentException("baseItemGroundworkChanged: oldVal wrong type");
					}
					//	When the db item is deleted it fires an event which is picked up here AND in the child bean
					//	The child bean sets its underlying baseItem to null so getValue() returns an Optional of null
					//	The order in which the event handlers are called is unpredictable
					childrenGroundwork.removeIf(pr -> (pr.getValue().isEmpty()) ||
						(pr.getValue().
							get().
							getKey().
							equals(((IGroundwork)(evt.getOldValue())).getKey())));
				}
			};

		baseItemHusbandryChanged = evt -> {
				if (childrenHusbandry == null)
				{
					return;
				}
				if (evt.getNewValue() != null)
				{
					if (!(evt.getNewValue() instanceof IHusbandry))
					{
						throw new IllegalArgumentException("baseItemHusbandryChanged: newVal wrong type");
					}
					childrenHusbandry.add(new HusbandryBean((IHusbandry)(evt.getNewValue())));
				}
				else if (evt.getOldValue() != null)
				{
					if (!(evt.getOldValue() instanceof IHusbandry))
					{
						throw new IllegalArgumentException("baseItemHusbandryChanged: oldVal wrong type");
					}
					//	When the db item is deleted it fires an event which is picked up here AND in the child bean
					//	The child bean sets its underlying baseItem to null so getValue() returns an Optional of null
					//	The order in which the event handlers are called is unpredictable
					childrenHusbandry.removeIf(pr -> (pr.getValue().isEmpty()) ||
						(pr.getValue().
							get().
							getKey().
							equals(((IHusbandry)(evt.getOldValue())).getKey())));
				}
			};

		baseItemPlantNoteChanged = evt -> {
				if (childrenPlantNote == null)
				{
					return;
				}
				if (evt.getNewValue() != null)
				{
					if (!(evt.getNewValue() instanceof IPlantNote))
					{
						throw new IllegalArgumentException("baseItemPlantNoteChanged: newVal wrong type");
					}
					childrenPlantNote.add(new PlantNoteBean((IPlantNote)(evt.getNewValue())));
				}
				else if (evt.getOldValue() != null)
				{
					if (!(evt.getOldValue() instanceof IPlantNote))
					{
						throw new IllegalArgumentException("baseItemPlantNoteChanged: oldVal wrong type");
					}
					//	When the db item is deleted it fires an event which is picked up here AND in the child bean
					//	The child bean sets its underlying baseItem to null so getValue() returns an Optional of null
					//	The order in which the event handlers are called is unpredictable
					childrenPlantNote.removeIf(pr -> (pr.getValue().isEmpty()) ||
						(pr.getValue().
							get().
							getKey().
							equals(((IPlantNote)(evt.getOldValue())).getKey())));
				}
			};

		baseItemProductChanged = evt -> {
				if (childrenProduct == null)
				{
					return;
				}
				if (evt.getNewValue() != null)
				{
					if (!(evt.getNewValue() instanceof IProduct))
					{
						throw new IllegalArgumentException("baseItemProductChanged: newVal wrong type");
					}
					childrenProduct.add(new ProductBean((IProduct)(evt.getNewValue())));
				}
				else if (evt.getOldValue() != null)
				{
					if (!(evt.getOldValue() instanceof IProduct))
					{
						throw new IllegalArgumentException("baseItemProductChanged: oldVal wrong type");
					}
					//	When the db item is deleted it fires an event which is picked up here AND in the child bean
					//	The child bean sets its underlying baseItem to null so getValue() returns an Optional of null
					//	The order in which the event handlers are called is unpredictable
					childrenProduct.removeIf(pr -> (pr.getValue().isEmpty()) ||
						(pr.getValue().
							get().
							getKey().
							equals(((IProduct)(evt.getOldValue())).getKey())));
				}
			};

		baseItemReminderChanged = evt -> {
				if (childrenReminder == null)
				{
					return;
				}
				if (evt.getNewValue() != null)
				{
					if (!(evt.getNewValue() instanceof IReminder))
					{
						throw new IllegalArgumentException("baseItemReminderChanged: newVal wrong type");
					}
					childrenReminder.add(new ReminderBean((IReminder)(evt.getNewValue())));
				}
				else if (evt.getOldValue() != null)
				{
					if (!(evt.getOldValue() instanceof IReminder))
					{
						throw new IllegalArgumentException("baseItemReminderChanged: oldVal wrong type");
					}
					//	When the db item is deleted it fires an event which is picked up here AND in the child bean
					//	The child bean sets its underlying baseItem to null so getValue() returns an Optional of null
					//	The order in which the event handlers are called is unpredictable
					childrenReminder.removeIf(pr -> (pr.getValue().isEmpty()) ||
						(pr.getValue().
							get().
							getKey().
							equals(((IReminder)(evt.getOldValue())).getKey())));
				}
			};

		baseItemSaleItemChanged = evt -> {
				if (childrenSaleItem == null)
				{
					return;
				}
				if (evt.getNewValue() != null)
				{
					if (!(evt.getNewValue() instanceof ISaleItem))
					{
						throw new IllegalArgumentException("baseItemSaleItemChanged: newVal wrong type");
					}
					childrenSaleItem.add(new SaleItemBean((ISaleItem)(evt.getNewValue())));
				}
				else if (evt.getOldValue() != null)
				{
					if (!(evt.getOldValue() instanceof ISaleItem))
					{
						throw new IllegalArgumentException("baseItemSaleItemChanged: oldVal wrong type");
					}
					//	When the db item is deleted it fires an event which is picked up here AND in the child bean
					//	The child bean sets its underlying baseItem to null so getValue() returns an Optional of null
					//	The order in which the event handlers are called is unpredictable
					childrenSaleItem.removeIf(pr -> (pr.getValue().isEmpty()) ||
						(pr.getValue().
							get().
							getKey().
							equals(((ISaleItem)(evt.getOldValue())).getKey())));
				}
			};

		baseItemToDoListChanged = evt -> {
				if (childrenToDoList == null)
				{
					return;
				}
				if (evt.getNewValue() != null)
				{
					if (!(evt.getNewValue() instanceof IToDoList))
					{
						throw new IllegalArgumentException("baseItemToDoListChanged: newVal wrong type");
					}
					childrenToDoList.add(new ToDoListBean((IToDoList)(evt.getNewValue())));
				}
				else if (evt.getOldValue() != null)
				{
					if (!(evt.getOldValue() instanceof IToDoList))
					{
						throw new IllegalArgumentException("baseItemToDoListChanged: oldVal wrong type");
					}
					//	When the db item is deleted it fires an event which is picked up here AND in the child bean
					//	The child bean sets its underlying baseItem to null so getValue() returns an Optional of null
					//	The order in which the event handlers are called is unpredictable
					childrenToDoList.removeIf(pr -> (pr.getValue().isEmpty()) ||
						(pr.getValue().
							get().
							getKey().
							equals(((IToDoList)(evt.getOldValue())).getKey())));
				}
			};


		baseItemCroppingActualChanged = evt -> {
			if (childrenCroppingActual == null)
			{
				return;
			}
			if (evt.getNewValue() != null)
			{
				if (!(evt.getNewValue() instanceof ICroppingActual))
				{
					throw new IllegalArgumentException("baseItemCroppingActualChanged: newVal wrong type");
				}
				childrenCroppingActual.add(new CroppingActualBean((ICroppingActual)(evt.getNewValue())));
			}
			else if (evt.getOldValue() != null)
			{
				if (!(evt.getOldValue() instanceof ICroppingActual))
				{
					throw new IllegalArgumentException("baseItemCroppingActualChanged: oldVal wrong type");
				}
				//	When the db item is deleted it fires an event which is picked up here AND in the child bean
				//	The child bean sets its underlying baseItem to null so getValue() returns an Optional of null
				//	The order in which the event handlers are called is unpredictable
				childrenCroppingActual.removeIf(pr -> (pr.getValue().isEmpty()) ||
						(pr.getValue().
								get().
								getKey().
								equals(((ICroppingActual)(evt.getOldValue())).getKey())));
			}
		};

		//	TODO	handle Review
	}
	private void addBaseListeners()
	{
        if (baseItem == null) return;
		baseItem.addPropertyChangeListener("deleted", baseItemDeleted);
		baseItem.addPropertyChangeListener("replaced", baseItemReplaced);

		baseItem.addPropertyChangeListener("AfflictionEvent", baseItemAfflictionEventChanged);

		baseItem.addPropertyChangeListener("Groundwork", baseItemGroundworkChanged);

		baseItem.addPropertyChangeListener("Husbandry", baseItemHusbandryChanged);

		baseItem.addPropertyChangeListener("PlantNote", baseItemPlantNoteChanged);

		baseItem.addPropertyChangeListener("Product", baseItemProductChanged);

		baseItem.addPropertyChangeListener("Reminder", baseItemReminderChanged);

		baseItem.addPropertyChangeListener("SaleItem", baseItemSaleItemChanged);

		baseItem.addPropertyChangeListener("ToDoList", baseItemToDoListChanged);

		baseItem.addPropertyChangeListener("CroppingActual", baseItemCroppingActualChanged);

		//	TODO	handle Review
	}
	private void removeBaseListeners()
	{
        if (baseItem == null) return;
		baseItem.removePropertyChangeListener("deleted", baseItemDeleted);
		baseItem.removePropertyChangeListener("replaced", baseItemReplaced);

		baseItem.removePropertyChangeListener("AfflictionEvent", baseItemAfflictionEventChanged);

		baseItem.removePropertyChangeListener("Groundwork", baseItemGroundworkChanged);

		baseItem.removePropertyChangeListener("Husbandry", baseItemHusbandryChanged);

		baseItem.removePropertyChangeListener("PlantNote", baseItemPlantNoteChanged);

		baseItem.removePropertyChangeListener("Product", baseItemProductChanged);

		baseItem.removePropertyChangeListener("Reminder", baseItemReminderChanged);

		baseItem.removePropertyChangeListener("SaleItem", baseItemSaleItemChanged);

		baseItem.removePropertyChangeListener("ToDoList", baseItemToDoListChanged);

		baseItem.removePropertyChangeListener("CroppingActual", baseItemCroppingActualChanged);

		//	TODO	handle Review
	}

	@Override
	public String toString()
	{
		return "PlantVarietyBean wrapping " + baseItem;
	}

}

