/*
 * Copyright (C) 2021,2022 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
    3.0.0	First version
    3.0.4	Comment handling
 */

package uk.co.gardennotebook.fxbean;

import javafx.beans.property.*;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
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 uk.co.gardennotebook.spi.*;
import uk.co.gardennotebook.util.StoryLineTree;

import java.beans.PropertyChangeListener;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 *	The crop rotation groups as used to avoid disease build up, etc.
	*
	*	@author	Andy Gegg
	*	@version	3.0.4
	*	@since	3.0.0
*/
final public class CropRotationGroupBean implements INotebookBean
{
	private static final Logger LOGGER = LogManager.getLogger();

	private ICropRotationGroup baseItem = null;

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

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

	private final SimpleStringProperty nameProperty = new SimpleStringProperty(this, "name", "");
	private final ChangeListener<String> nameListener = this::onNameChange;
    private final ReadOnlyBooleanWrapper duplicateNameProperty = new ReadOnlyBooleanWrapper(this, "duplicateName", false);  //  2.2.0

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

	/*
	*	BE VERY CAREFUL
	* It's really easy to start an endless loop as this bean sets up a bean for the next CRG
	*  which sets up a bean for the next CRG and on and on endlessly
	 */
	private SimpleObjectProperty<CropRotationGroupBean> subsequentCropGroupProperty = null;
	private final ChangeListener<CropRotationGroupBean> subsequentCropGroupIdListener = this::onSubsequentCropGroupIdChange;
	private final ReadOnlyBooleanWrapper hasSubsequentCropGroupProperty = new ReadOnlyBooleanWrapper(this, "hasSubsequentCropGroup", false);

	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<ICropRotationGroup> beanCommentHandler;	//	2.9.6
	private final ReadOnlyStringWrapper commentTextProperty = new ReadOnlyStringWrapper(this, "commentText", "");	//	2.9.6

	private ObservableList<PlantSpeciesBean> childrenPlantSpecies = null;
	private PropertyChangeListener baseItemPlantSpeciesChanged;

	/**
	*	Construct an 'empty' Bean.  Set the various property values then call save() to create the new CropRotationGroupBean
	*/
	public CropRotationGroupBean()
	{
		this(null);
	}
	/**
	*	Construct a Bean wrapping the given CropRotationGroup
	*	If the parameter is null a new 'empty' Bean will be constructed
	*
	*	@param	initialValue	the CropRotationGroup to wrap.  If null an 'empty' bean will be constructed
	*
	*/
	public CropRotationGroupBean(final ICropRotationGroup initialValue)
	{
//		EntryMessage log4jEntryMsg = LOGGER.traceEntry("CropRotationGroupBean: constructor: {}", initialValue);
		ChangeListener<Boolean> saveRequiredListener = (obs, old, nval) -> {
			if (nval && !explicitSave)
			{
				explicitSave = true;
				ITrug server = TrugServer.getTrugServer().getTrug();
				explicitBuilder = server.getCropRotationGroupBuilder(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();
//		LOGGER.debug("constructor: after setValues");

		addListeners();
//		LOGGER.debug("constructor: after addListeners");
		declareBaseListeners();
//		LOGGER.debug("constructor: after declareBaseListeners");
		addBaseListeners();
//		LOGGER.traceExit(log4jEntryMsg);
	}

	/**
	*	Returns all CropRotationGroup items wrapped as CropRotationGroupBean.
	*
	*	@return	a collection of CropRotationGroupBean 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<CropRotationGroupBean> fetchAll() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("fetchAll()");
		ITrug server = TrugServer.getTrugServer().getTrug();
		ICropRotationGroupLister gal = server.getCropRotationGroupLister();
		List<CropRotationGroupBean> ll = gal.fetch().stream()
					.collect(ArrayList::new, (c, e) -> c.add(new CropRotationGroupBean(e)), ArrayList::addAll);
		LOGGER.traceExit();
		return FXCollections.observableArrayList(ll);
	}

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

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

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

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

	@Override
	public boolean sameAs(final INotebookBean other)
	{
		if (other == null || ((CropRotationGroupBean)other).baseItem == null || baseItem == null)
		{
			return false;
		}
		if (other.getType() != NotebookEntryType.CROPROTATIONGROUP)
		{
			return false;
		}
		return baseItem.sameAs(((CropRotationGroupBean)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.getCropRotationGroupBuilder(baseItem).canDelete();
			canDeleteProperty = new ReadOnlyBooleanWrapper(this, "canDelete", canDel);
		}
		return canDeleteProperty.getReadOnlyProperty();
	}

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

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

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

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

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

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

	public String getName()
	{
		return nameProperty.get();
	}
	public void setName(final String newVal)
	{
		nameProperty.set(newVal);
	}
	/**
	*	Wraps the Name value of the CropRotationGroup
	*
	*	@return	a writable property wrapping the name attribute
	*/
	public StringProperty nameProperty()
	{
		return nameProperty;
	}

	private void onNameChange(ObservableValue<? extends String> obs, String old, String nval)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("onNameChange(): old={}, new={}", old, nval);
		if (explicitSave)
		{
LOGGER.debug("onNameChange(): explicitSave");
			try
			{
				explicitBuilder.name(nval);
			} catch (GNDBException ex) {
				throw new GNDBRuntimeException(ex);
			}
		}
		else
		{
LOGGER.debug("onNameChange(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			try
			{
				baseItem = server.getCropRotationGroupBuilder(baseItem).name(nval).save();
			} catch (GNDBException ex) {
				throw new GNDBRuntimeException(ex);
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
	}
    
    /**
     * Use this to check if the name being applied is a duplicate of an existing name.
     * NB relies on calling {@code checkForDuplicateName} on focusLost.
     * 
     * @return a read-only indication that the name being set is a duplicate of an existing name
     */
    public ReadOnlyBooleanProperty duplicateNameProperty()
    {
        return duplicateNameProperty.getReadOnlyProperty();
    }

    /**
     *  Must be called from the editor when the user has finished entering a new name value,
     * typically on a lost focus event.
     * 
     * @param newVal    the name the user is attempting to give
     * @return  true if newVal duplicates an existing name
     * 
     * @since 2.2.0
     */    
    public boolean checkForDuplicateName(final String newVal)
    {
        boolean duplicate = false;
    
		if (explicitSave)
		{
LOGGER.debug("checkNameDuplicate(): explicitSave");
			try
			{
				duplicate = explicitBuilder.isNameDuplicate(newVal);
			} catch (GNDBException ex) {
				throw new GNDBRuntimeException(ex);
			}
		}
		else
		{
LOGGER.debug("checkNameDuplicate(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			try
			{
				duplicate = server.getCropRotationGroupBuilder(baseItem).isNameDuplicate(newVal);
			} catch (GNDBException ex) {
				throw new GNDBRuntimeException(ex);
			}
        }
        duplicateNameProperty.set(duplicate);
        return duplicate;
    }

	public String getDescription()
	{
		return descriptionProperty.get();
	}
	public void setDescription(final String newVal)
	{
		descriptionProperty.set(newVal);
	}
	/**
	*	Wraps the Description value of the CropRotationGroup
	*
	*	@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.getCropRotationGroupBuilder(baseItem).description(nval).save();
			} catch (GNDBException ex) {
				throw new GNDBRuntimeException(ex);
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
	}

	public boolean hasSubsequentCropGroup()
	{
		return hasSubsequentCropGroupProperty().getValue();
	}
	/**
	 *	Use this to check if the PlantVariety parent of the Husbandry this Bean wraps is present
	 *
	 *	@return	true if this Husbandry is linked to a PlantVariety
	 */
	public ReadOnlyBooleanProperty hasSubsequentCropGroupProperty()
	{
		return hasSubsequentCropGroupProperty.getReadOnlyProperty();
	}
	public CropRotationGroupBean getSubsequentCropGroup()
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("getSubsequentCropGroup()");
		if (subsequentCropGroupProperty == null)
		{
			subsequentCropGroupProperty = new SimpleObjectProperty<>(this, "subsequentCropGroup", null);
			subsequentCropGroupProperty.setValue(new CropRotationGroupBean(baseItem.getSubsequentCropGroup().orElse(null)) );
		}
		return subsequentCropGroupProperty.get();
	}
	public void setSubsequentCropGroup(final CropRotationGroupBean bean)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("setSubsequentCropGroup(): bean: {}", bean);
		subsequentCropGroupProperty.set(bean);
	}
	public void setSubsequentCropGroup(final ICropRotationGroup item)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("setSubsequentCropGroup(): item: {}", item);
		subsequentCropGroupProperty().set(new CropRotationGroupBean(item));
	}
	/**
	 *	Wraps the SubsequentCropGroup value of the CropRotationGroup
	 *
	 *	@return	a writable property wrapping the subsequentCropGroup attribute
	 */
	public ObjectProperty<CropRotationGroupBean> subsequentCropGroupProperty()
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("subsequentCropGroupProperty()");
		if (subsequentCropGroupProperty == null)
		{
			subsequentCropGroupProperty = new SimpleObjectProperty<>(this, "subsequentCropGroup", null);
			subsequentCropGroupProperty.setValue(new CropRotationGroupBean(baseItem.getSubsequentCropGroup().orElse(null)) );
		}
		return subsequentCropGroupProperty;
	}

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

	public LocalDateTime getLastUpdated()
	{
		return lastUpdatedProperty.get();
	}
	/**
	*	Wraps the LastUpdated value of the CropRotationGroup
	*	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 CropRotationGroup
	*	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 PlantSpecies of this CropRotationGroup or an empty list
	*
	*	@return	A list of PlantSpecies 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<PlantSpeciesBean> getPlantSpecies() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("getPlantSpecies()");
		if (childrenPlantSpecies == null)
		{
			childrenPlantSpecies = FXCollections.observableArrayList();
			ITrug server = TrugServer.getTrugServer().getTrug();
			for (IPlantSpecies ix : server.getPlantSpeciesLister().cropRotationGroup(baseItem).fetch())
			{
				childrenPlantSpecies.add(new PlantSpeciesBean(ix));
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
		return childrenPlantSpecies;
	}

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

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

	@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 CropRotationGroup
LOGGER.debug("addComment(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			baseItem = server.getCropRotationGroupBuilder(baseItem).addComment(text).save();
			setValues();	//	2.9.6
		}
		LOGGER.traceExit(log4jEntryMsg);
	}	//	addComment()

	@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 CropRotationGroup
			LOGGER.debug("addComment(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			baseItem = server.getCropRotationGroupBuilder(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 CropRotationGroup
LOGGER.debug("changeCommentText(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			baseItem = server.getCropRotationGroupBuilder(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 CropRotationGroup
LOGGER.debug("changeCommentDate(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			baseItem = server.getCropRotationGroupBuilder(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 CropRotationGroup
LOGGER.debug("deleteComment(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			baseItem = server.getCropRotationGroupBuilder(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 CropRotationGroup 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("CropRotationGroupBean: 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()

	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 CropRotationGroup 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.getCropRotationGroupBuilder(baseItem).delete();
		}
	}	//	delete()

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

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

	private void setDefaults()
	{
		saveRequiredProperty.setValue(false);
		nameProperty.setValue("");
		descriptionProperty.setValue("");
//		subsequentCropGroupProperty.setValue(null);
		subsequentCropGroupProperty = null;
		hasSubsequentCropGroupProperty.setValue(false);
		lastUpdatedProperty.setValue(LocalDateTime.now());
		createdProperty.setValue(LocalDateTime.now());
		childrenPlantSpecies = null;
		baseItemPlantSpeciesChanged = null;

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

	private void setValues()
	{
		saveRequiredProperty.setValue(false);
		nameProperty.setValue(baseItem.getName());
		descriptionProperty.setValue(baseItem.getDescription().orElse(""));
		//	WARNING risk of endless loop
		hasSubsequentCropGroupProperty.setValue(baseItem.getSubsequentCropGroup().isPresent());
//		if (baseItem.getSubsequentCropGroup().isPresent())
//		{
//			subsequentCropGroupProperty.setValue(new CropRotationGroupBean(baseItem.getSubsequentCropGroup().get()));
//		}
		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()
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("addListeners()");
		nameProperty.addListener(nameListener);
		descriptionProperty.addListener(descriptionListener);
		LOGGER.debug("after description");
//		subsequentCropGroupProperty.addListener(subsequentCropGroupIdListener);
		LOGGER.traceExit(log4jEntryMsg);
	}
	private void removeListeners()
	{
		nameProperty.removeListener(nameListener);
		descriptionProperty.removeListener(descriptionListener);
		subsequentCropGroupProperty.removeListener(subsequentCropGroupIdListener);
	}
	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 = (ICropRotationGroup)(evt.getNewValue());
					setValues();
					addBaseListeners();
				}
			};

		baseItemPlantSpeciesChanged = evt -> {
				if (childrenPlantSpecies == null)
				{
					return;
				}
				if (evt.getNewValue() != null)
				{
					if (!(evt.getNewValue() instanceof IPlantSpecies))
					{
						throw new IllegalArgumentException("baseItemPlantSpeciesChanged: newVal wrong type");
					}
					childrenPlantSpecies.add(new PlantSpeciesBean((IPlantSpecies)(evt.getNewValue())));
				}
				else if (evt.getOldValue() != null)
				{
					if (!(evt.getOldValue() instanceof IPlantSpecies))
					{
						throw new IllegalArgumentException("baseItemPlantSpeciesChanged: 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
					childrenPlantSpecies.removeIf(pr -> (pr.getValue().isEmpty()) ||
						(pr.getValue().
							get().
							getKey().
							equals(((IPlantSpecies)(evt.getOldValue())).getKey())));
				}
			};

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

		baseItem.addPropertyChangeListener("PlantSpecies", baseItemPlantSpeciesChanged);

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

		baseItem.removePropertyChangeListener("PlantSpecies", baseItemPlantSpeciesChanged);

	}

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

}

