/*
 * Copyright (C) 2018-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
	2.2.0   Better handling for duplicate names
    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.4	Comment handling
 */

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.util.ArrayList;
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;

/**
	*	These are the various afflictions observed.
	*
	*	@author	Andy Gegg
	*	@version	3.0.4
	*	@since	1.0
*/
final public class AfflictionBean implements INotebookBean
{
	private static final Logger LOGGER = LogManager.getLogger();

	private IAffliction baseItem = null;

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

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


	/*
	*	An actual type of pest, disease or death, e.g. lily beetle, blight.<BR>
@apiNote
Note that this is optional - I think it's too restrictive to force users to create AfflictionClasses before they can specify an actual Affliction.
There's no option to show 'all AfflictionEvents caused by a pest', for instance.
Having this field mandatory also requires AfflictionClass combos on Husbandry and AfflictionEvent editors.
	*/
	private final SimpleObjectProperty<AfflictionClassBean> parentAfflictionClassProperty = new SimpleObjectProperty<>(this, "afflictionClass", null);
	private final ChangeListener<AfflictionClassBean> afflictionClassIdListener = this::onAfflictionClassIdChange;
	private final ReadOnlyBooleanWrapper hasParentAfflictionClassProperty = new ReadOnlyBooleanWrapper(this, "hasAfflictionClass", false);
	private final SimpleStringProperty nameProperty = new SimpleStringProperty(this, "name", "");
	private final ChangeListener<String> nameListener = this::onNameChange;
    //  2.2.0
    private final ReadOnlyBooleanWrapper duplicateNameProperty = new ReadOnlyBooleanWrapper(this, "duplicateName", false);
	private final SimpleStringProperty descriptionProperty = new SimpleStringProperty(this, "description", "");
	private final ChangeListener<String> descriptionListener = this::onDescriptionChange;
	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 ObservableList<CommentBean> childrenComment = null;	//	2.9.6

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

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

	private BeanCommentHandler<IAffliction> beanCommentHandler;
	private final ReadOnlyStringWrapper commentTextProperty = new ReadOnlyStringWrapper(this, "commentText", "");
	/**
	*	Construct an 'empty' Bean.  Set the various property values then call save() to create the new AfflictionBean
	*/
	public AfflictionBean()
	{
		this(null);
	}
	/**
	*	Construct a Bean wrapping the given Affliction
	*	If the parameter is null a new 'empty' Bean will be constructed
	*
	*	@param	initialValue	the Affliction to wrap.  If null an 'empty' bean will be constructed
	*
	*/
	public AfflictionBean(final IAffliction initialValue)
	{
		ChangeListener<Boolean> saveRequiredListener = (obs, old, nval) -> {
			if (nval && !explicitSave)
			{
				explicitSave = true;
				ITrug server = TrugServer.getTrugServer().getTrug();
				explicitBuilder = server.getAfflictionBuilder(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 Affliction items wrapped as AfflictionBean.
	*
	*	@return	a collection of AfflictionBean 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<AfflictionBean> fetchAll() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("fetchAll()");
		ITrug server = TrugServer.getTrugServer().getTrug();
		IAfflictionLister gal = server.getAfflictionLister();
		List<AfflictionBean> ll = gal.fetch().stream()
					.collect(ArrayList::new, (c, e) -> c.add(new AfflictionBean(e)), ArrayList::addAll);
		LOGGER.traceExit();
		return FXCollections.observableArrayList(ll);
	}

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

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

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

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

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

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

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

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

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

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

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

	public boolean hasAfflictionClass()
	{
		return hasAfflictionClassProperty().getValue();
	}
	/**
	*	Use this to check if the AfflictionClass parent of the Affliction this Bean wraps is present
	*
	*	@return	true if this Affliction is linked to a AfflictionClass
	*/
	public ReadOnlyBooleanProperty hasAfflictionClassProperty()
	{
		return hasParentAfflictionClassProperty.getReadOnlyProperty();
	}
	public AfflictionClassBean getAfflictionClass()
	{
		return afflictionClassProperty().getValue();
	}
	public void setAfflictionClass(final AfflictionClassBean bean)
	{
		afflictionClassProperty().setValue(bean);
	}
	public void setAfflictionClass(final IAfflictionClass item)
	{
		afflictionClassProperty().setValue(new AfflictionClassBean(item));
	}
	/**
	*	Returns the AfflictionClass parent of the Affliction this Bean wraps
	*	Call hasAfflictionClass() first to check if this value is set
	*
	*	@return	the AfflictionClass parent of the Affliction this Bean wraps
	*/
	public ObjectProperty<AfflictionClassBean> afflictionClassProperty()
	{
		return parentAfflictionClassProperty;
	}

	/**
	*	Handle changes to the AfflictionClassId 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 onAfflictionClassIdChange(ObservableValue<? extends AfflictionClassBean> obs, AfflictionClassBean old, AfflictionClassBean nval)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("onAfflictionClassIdChange(): old={}, new={}", old, nval);
		if (nval != null && nval.sameAs(old))
		{
LOGGER.debug("onAfflictionClassIdChange(): nval is sameAs old");
			return;
		}
		hasParentAfflictionClassProperty.set(nval != null);

		if ((nval != null) && !nval.isNew())
		{
			if (explicitSave)
			{
LOGGER.debug("onAfflictionClassIdChange(): explicitSave");
				explicitBuilder.afflictionClass(nval.get().get());
			}
			else
			{
LOGGER.debug("onAfflictionClassIdChange(): NOT explicitSave");
				ITrug server = TrugServer.getTrugServer().getTrug();
				//	the Builder will send an event to the baseItem to say it's been replaced
				try
				{
					server.getAfflictionBuilder(baseItem).afflictionClass(nval.get().get()).save();
				} catch (GNDBException ex) {
					throw new GNDBRuntimeException(ex);
				}
			}
		}
		else if (nval == null)
		{
			if (explicitSave)
			{
				explicitBuilder.afflictionClass(null);
			}
			else
			{
LOGGER.debug("onAfflictionClassIdChange(): NOT explicitSave");
				ITrug server = TrugServer.getTrugServer().getTrug();
				//	the Builder will send an event to the baseItem to say it's been replaced
				try
				{
					server.getAfflictionBuilder(baseItem).afflictionClass(null).save();
				} catch (GNDBException ex) {
					throw new GNDBRuntimeException(ex);
				}
			}
		}

		LOGGER.traceExit(log4jEntryMsg);
	}


	public String getName()
	{
		return nameProperty.get();
	}
	public void setName(final String newVal)
	{
		nameProperty.set(newVal);
	}
	/**
	*	Wraps the Name value of the Affliction
	*
	*	@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.getAfflictionBuilder(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
     * 
     * @since 2.2.0
     */
    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.getAfflictionBuilder(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 Affliction
	*
	*	@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.getAfflictionBuilder(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 Affliction
	*	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 Affliction
	*	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 Affliction 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().affliction(baseItem).fetch())
			{
				childrenAfflictionEvent.add(new AfflictionEventBean(ix));
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
		return childrenAfflictionEvent;
	}

	/**
	*	Return a list of any Husbandry of this Affliction 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().affliction(baseItem).fetch())
			{
				childrenHusbandry.add(new HusbandryBean(ix));
			}
		}
		LOGGER.traceExit(log4jEntryMsg);
		return childrenHusbandry;
	}

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

		//	2.9.6
		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);

		if (explicitSave)
		{
LOGGER.debug("addComment(): explicitSave");
		}
		else
		{	//	this cannot be a new instance of the parent Affliction
LOGGER.debug("addComment(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			baseItem = server.getAfflictionBuilder(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 Affliction
			LOGGER.debug("addComment(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			baseItem = server.getAfflictionBuilder(baseItem).addComment(comment.getComment()).save();
			setValues();
		}
		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;

		if (explicitSave)
		{
LOGGER.debug("changeCommentText(): explicitSave");
		}
		else
		{	//	this cannot be a new instance of the parent Affliction
LOGGER.debug("changeCommentText(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			baseItem = server.getAfflictionBuilder(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 Affliction
LOGGER.debug("changeCommentDate(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			baseItem = server.getAfflictionBuilder(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 Affliction
LOGGER.debug("deleteComment(): NOT explicitSave");
			ITrug server = TrugServer.getTrugServer().getTrug();
			baseItem = server.getAfflictionBuilder(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;
	}

	@Override
	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 Affliction 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("AfflictionBean: cannot save at this time - mandatory values not set");
		}

		baseItem = explicitBuilder.save();
		setValues();	//	2.9.6
		newItem = false;
		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 Affliction 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.getAfflictionBuilder(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("");
		lastUpdatedProperty.setValue(LocalDateTime.now());
		createdProperty.setValue(LocalDateTime.now());
		childrenAfflictionEvent = null;
		baseItemAfflictionEventChanged = null;
		childrenHusbandry = null;
		baseItemHusbandryChanged = null;

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

	private void setValues()
	{
		saveRequiredProperty.setValue(false);
		if (baseItem.getAfflictionClass().isPresent())
		{
			hasParentAfflictionClassProperty.set(true);
			parentAfflictionClassProperty.setValue(new AfflictionClassBean(baseItem.getAfflictionClass().get()));
		}
		else
		{
			hasParentAfflictionClassProperty.set(false);
			parentAfflictionClassProperty.setValue(null);
		}
		nameProperty.setValue(baseItem.getName());
		descriptionProperty.setValue(baseItem.getDescription().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()
	{
		parentAfflictionClassProperty.addListener(afflictionClassIdListener);
		nameProperty.addListener(nameListener);
		descriptionProperty.addListener(descriptionListener);
	}
	private void removeListeners()
	{
		parentAfflictionClassProperty.removeListener(afflictionClassIdListener);
		nameProperty.removeListener(nameListener);
		descriptionProperty.removeListener(descriptionListener);
	}
	private void declareBaseListeners()
	{
		// handle changes to the base item itself
		baseItemDeleted = evt -> {
				removeListeners();
				removeBaseListeners();
				setDefaults();
				baseItem = null;
			};
		baseItemReplaced = evt -> {
//				LOGGER.debug("baseItemReplaced: newValue: {}", evt.getNewValue());
				if (evt.getNewValue() != null)
				{
					removeBaseListeners();
					baseItem = (IAffliction)(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())));
				}
			};

		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())));
				}
			};

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

		baseItem.addPropertyChangeListener("AfflictionEvent", baseItemAfflictionEventChanged);

		baseItem.addPropertyChangeListener("Husbandry", baseItemHusbandryChanged);

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

		baseItem.removePropertyChangeListener("AfflictionEvent", baseItemAfflictionEventChanged);

		baseItem.removePropertyChangeListener("Husbandry", baseItemHusbandryChanged);

	}

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

}

