/*
 *
 *  Copyright (C) 2021, 2022 Andrew Gegg
 *
 * 	This file is part of the Gardeners Notebook application
 *
 *  The Gardeners 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.List;
import java.util.Objects;
import java.util.Optional;

/**
 *	The actual plant species/varieties used in the implementation (or intended implementation) of a Cropping Plan
 *
 *	@author	Andy Gegg
 *	@version	3.0.4
 *	@since	1.0
 */
public final class CroppingActualBean implements INotebookBean
{
    private static final Logger LOGGER = LogManager.getLogger();

    private ICroppingActual baseItem = null;

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

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

    private final SimpleObjectProperty<CroppingPlanBean> parentCroppingPlanProperty = new SimpleObjectProperty<>(this, "croppingPlan", null);
//    private final ReadOnlyObjectWrapper<CroppingPlanBean> parentCroppingPlanProperty = new ReadOnlyObjectWrapper<>(this, "croppingPlan", null);
    private final ChangeListener<CroppingPlanBean> croppingPlanIdListener = this::onCroppingPlanIdChange;

    /*
    *	Always required as CroppingActual always refers to a plant.
The activity is for plants of this species.
@apiNote
plantVarietyId may or may not be given; if absent the CroppingActual is for all (current) e.g. tomato varieties.
This 'denormalises' the model but enables easy searches for e.g. 'all tomatoes'
    */
    private final SimpleObjectProperty<PlantSpeciesBean> parentPlantSpeciesProperty = new SimpleObjectProperty<>(this, "plantSpecies", null);
    private final ChangeListener<PlantSpeciesBean> plantSpeciesIdListener = this::onPlantSpeciesIdChange;

    /*
    *	The CroppingActual is for plants of this variety.
@apiNote
If present, plantSpeciesId must be given.  This 'denormalises' the model but enables easy searches for e.g. 'all tomatoes'
    */
    private final SimpleObjectProperty<PlantVarietyBean> parentPlantVarietyProperty = new SimpleObjectProperty<>(this, "plantVariety", null);
    private final ChangeListener<PlantVarietyBean> plantVarietyIdListener = this::onPlantVarietyIdChange;
    private final ReadOnlyBooleanWrapper hasParentPlantVarietyProperty = new ReadOnlyBooleanWrapper(this, "hasPlantVariety", 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);

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

    /**
     *	Construct an 'empty' Bean.  Set the various property values then call save() to create the new CroppingActualBean
     */
    public CroppingActualBean()
    {
        this(null);
    }
    /**
     *	Construct a Bean wrapping the given CroppingActual
     *	If the parameter is null a new 'empty' Bean will be constructed
     *
     *	@param	initialValue	the CroppingActual to wrap.  If null an 'empty' bean will be constructed
     *
     */
    public CroppingActualBean(final ICroppingActual initialValue)
    {
        LOGGER.debug("constructor: initialValue: {}", initialValue);

        ChangeListener<Boolean> saveRequiredListener = (obs, old, nval) -> {
            if (nval && !explicitSave)
            {
                explicitSave = true;
                ITrug server = TrugServer.getTrugServer().getTrug();
                explicitBuilder = server.getCroppingActualBuilder(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;

        setValues();

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

    /**
     *	Returns all CroppingActual items wrapped as CroppingActualBean.
     *
     *  @param croppingPlan fetch the CroppingActual items for this CroppingPlan.  Must not be null.
     *
     *	@return	a collection of CroppingActualBean 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<CroppingActualBean> fetchAll(CroppingPlanBean croppingPlan) throws GNDBException
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("fetchAll(): croppingPlan: {}", croppingPlan);

        Objects.requireNonNull(croppingPlan, "CroppingActualBean: fetchAll(): null argument");

        ITrug server = TrugServer.getTrugServer().getTrug();
        ICroppingActualLister gal = server.getCroppingActualLister().croppingPlan(croppingPlan.get().orElse(null));
        List<CroppingActualBean> ll = gal.fetch().stream().map(CroppingActualBean::new).toList();
        LOGGER.traceExit();
        return FXCollections.observableArrayList(ll);
    }

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

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

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

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

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

    public String getCommonName()
    {
        if (!hasPlantVariety())
        {
            return parentPlantSpeciesProperty.getValue().getCommonName();
        }
        else
        {
            return parentPlantVarietyProperty.getValue().getCommonName();
        }
    }

    @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.getCroppingActualBuilder(baseItem).canDelete();
            canDeleteProperty = new ReadOnlyBooleanWrapper(this, "canDelete", canDel);
        }
        return canDeleteProperty.getReadOnlyProperty();
    }

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

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

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

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

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

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

    /**
     * Returns the NotebookEntryType of the enclosed item (PLANTSPECIES or PLANTVARIETY)
     *
     * @return  the type of the enclosed item
     */
    public NotebookEntryType getEnclosedItemType()
    {
        if (hasPlantVariety())
        {
            return NotebookEntryType.PLANTVARIETY;
        }
        return NotebookEntryType.PLANTSPECIES;
    }


    public CroppingPlanBean getCroppingPlan()
    {
        return croppingPlanProperty().getValue();
    }
    public void setCroppingPlan(final CroppingPlanBean bean)
    {
//        LOGGER.debug("setCroppingPlan(): {}, item");
        croppingPlanProperty().setValue(bean);
    }
    public void setCroppingPlan(final ICroppingPlan item)
    {
//        LOGGER.debug("setCroppingPlan(): {}, item");
        croppingPlanProperty().setValue(new CroppingPlanBean(item));
    }
    /**
     *	Returns the CroppingPlan parent of the CroppingActual this Bean wraps
     *
     *	@return	the CroppingPlan parent of the CroppingActual this Bean wraps
     */
    public ObjectProperty<CroppingPlanBean> croppingPlanProperty()
    {
        return parentCroppingPlanProperty;
    }

    /**
     *	Handle changes to the CroppingPlanId 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 onCroppingPlanIdChange(ObservableValue<? extends CroppingPlanBean> obs, CroppingPlanBean old, CroppingPlanBean nval)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("onCroppingPlanIdChange(): old={}, new={}", old, nval);
        if (nval == null)
        {	// this is an error condition and should be flagged
            LOGGER.debug("onCroppingPlanIdChange(): nval is null");
            return;
        }
        if (nval.sameAs(old))
        {
            LOGGER.debug("onCroppingPlanIdChange(): nval is sameAs old");
            return;
        }
        if (!nval.isNew())
        {
            if (explicitSave)
            {
                explicitBuilder.cropppingPlan(nval.get().get());
            }
            else
            {
                LOGGER.debug("onCroppingPlanIdChange(): NOT explicitSave");
                ITrug server = TrugServer.getTrugServer().getTrug();
                //	the Builder will send an event to the baseItem to say it's been replaced
                try
                {
                    server.getCroppingActualBuilder(baseItem).cropppingPlan(nval.get().get()).save();
                } catch (GNDBException ex) {
                    throw new GNDBRuntimeException(ex);
                }
            }
        }

        LOGGER.traceExit(log4jEntryMsg);
    }

    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 Husbandry this Bean wraps
     *
     *	@return	the PlantSpecies parent of the Husbandry 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.getCroppingActualBuilder(baseItem).plantSpecies(nval.get().get()).save();
                } catch (GNDBException ex) {
                    throw new GNDBRuntimeException(ex);
                }
            }
        }

        LOGGER.traceExit(log4jEntryMsg);
    }


    public boolean hasPlantVariety()
    {
        return hasPlantVarietyProperty().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 hasPlantVarietyProperty()
    {
        return hasParentPlantVarietyProperty.getReadOnlyProperty();
    }
    public PlantVarietyBean getPlantVariety()
    {
        return plantVarietyProperty().getValue();
    }
    public void setPlantVariety(final PlantVarietyBean bean)
    {
        plantVarietyProperty().setValue(bean);
    }
    public void setPlantVariety(final IPlantVariety item)
    {
        plantVarietyProperty().setValue(new PlantVarietyBean(item));
    }
    /**
     *	Returns the PlantVariety parent of the Husbandry this Bean wraps
     *	Call hasPlantVariety() first to check if this value is set
     *
     *	@return	the PlantVariety parent of the Husbandry this Bean wraps
     */
    public ObjectProperty<PlantVarietyBean> plantVarietyProperty()
    {
        return parentPlantVarietyProperty;
    }

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

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

        LOGGER.traceExit(log4jEntryMsg);
    }

    public LocalDateTime getLastUpdated()
    {
        return lastUpdatedProperty.get();
    }
    /**
     *	Wraps the LastUpdated value of the Husbandry
     *	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 Husbandry
     *	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();
    }

    @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;

        beanCommentHandler.addComment(text);

        if (explicitSave)
        {
            LOGGER.debug("addComment(): explicitSave");
        }
        else
        {	//	this cannot be a new instance of the parent CroppingActual
            LOGGER.debug("addComment(): NOT explicitSave");
            ITrug server = TrugServer.getTrugServer().getTrug();
            baseItem = server.getCroppingActualBuilder(baseItem).addComment(text).save();
            setValues();
        }
        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 CroppingActual item
            LOGGER.debug("addComment(): NOT explicitSave");
            ITrug server = TrugServer.getTrugServer().getTrug();
            baseItem = server.getCroppingActualBuilder(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)
        {
            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 CroppingActual
            LOGGER.debug("changeCommentText(): NOT explicitSave");
            ITrug server = TrugServer.getTrugServer().getTrug();
            baseItem = server.getCroppingActualBuilder(baseItem).changeComment(comment.get().get(), text).save();
            setValues();
        }
        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;

        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 CroppingActual
            LOGGER.debug("changeCommentDate(): NOT explicitSave");
            ITrug server = TrugServer.getTrugServer().getTrug();
            baseItem = server.getCroppingActualBuilder(baseItem).changeComment(comment.get().get(), date).save();
            setValues();
        }
        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 CroppingActual
            LOGGER.debug("deleteComment(): NOT explicitSave");
            ITrug server = TrugServer.getTrugServer().getTrug();
            baseItem = server.getCroppingActualBuilder(baseItem).deleteComment(comment.get().get()).save();
            setValues();
        }
        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 CroppingActual 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();	//	do this here so that explicitBuilder knows there's a change

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

        baseItem = explicitBuilder.save();
        LOGGER.debug("save(): after explicit save: baseItem: {}", baseItem);
        LOGGER.debug("save(): after explicitBuilder.save(): comments: {}", baseItem.getComments());
        setValues();
        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 CroppingActual 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.getCroppingActualBuilder(baseItem).delete();
        }
    }	//	delete()

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

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

    private void setDefaults()
    {
        saveRequiredProperty.setValue(false);
        lastUpdatedProperty.setValue(LocalDateTime.now());
        createdProperty.setValue(LocalDateTime.now());

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

    private void setValues()
    {
        saveRequiredProperty.setValue(false);
        parentCroppingPlanProperty.setValue(new CroppingPlanBean(baseItem.getCroppingPlan()));
        parentPlantSpeciesProperty.setValue(new PlantSpeciesBean(baseItem.getPlantSpecies()));
        if (baseItem.getPlantVariety().isPresent())
        {
            hasParentPlantVarietyProperty.set(true);
            parentPlantVarietyProperty.setValue(new PlantVarietyBean(baseItem.getPlantVariety().get()));
        }
        else
        {
            hasParentPlantVarietyProperty.set(false);
            parentPlantVarietyProperty.setValue(null);
        }

        lastUpdatedProperty.setValue(baseItem.getLastUpdated());
        createdProperty.setValue(baseItem.getCreated());

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

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

    private void addListeners()
    {
        parentCroppingPlanProperty.addListener(croppingPlanIdListener);
        parentPlantSpeciesProperty.addListener(plantSpeciesIdListener);
        parentPlantVarietyProperty.addListener(plantVarietyIdListener);
    }

    private void removeListeners()
    {
        parentCroppingPlanProperty.removeListener(croppingPlanIdListener);
        parentPlantSpeciesProperty.removeListener(plantSpeciesIdListener);
        parentPlantVarietyProperty.removeListener(plantVarietyIdListener);
    }

    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 = (ICroppingActual) (evt.getNewValue());
                setValues();
                addBaseListeners();
            }
        };

    }

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

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

}
