/*
 *
 *  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.time.Year;
import java.util.List;
import java.util.Optional;

/**
 * This records the type of crop grown in a given location in a given planting year.  For instance, 'Alliums' in 'Bed 1'
 * in 2021.  Details of the actual plant species and, possibly, varieties can be added through the CroppingActual table.
 * Entries for past years are records of what was grown, entries for future years are to record the intended rotation of
 * crops through the various beds; the intention is that more detail is added (in CroppingActual) as plants are
 * ordered and sown.
 *
 *	@author	Andy Gegg
 *	@version	3.0.4
 *	@since	3.0.0
 */
public final class CroppingPlanBean implements INotebookBean
{
    private static final Logger LOGGER = LogManager.getLogger();

    private ICroppingPlan baseItem = null;

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

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

    private final SimpleObjectProperty<Year> yearOfPlanProperty = new SimpleObjectProperty<>(this, "yearInOfPlan", null);
    private final ChangeListener<Year> yearOfPlanListener = this::onYearOfPlanChange;

    /*
     *	Location where the activity is planned to take place
     */
    private final SimpleObjectProperty<LocationBean> parentLocationProperty = new SimpleObjectProperty<>(this, "location", null);
    private final ChangeListener<LocationBean> locationIdListener = this::onLocationIdChange;
//    private final ReadOnlyBooleanWrapper hasParentLocationProperty = new ReadOnlyBooleanWrapper(this, "hasLocation", false);

    private final SimpleObjectProperty<CropRotationGroupBean> parentCropRotationGroupProperty = new SimpleObjectProperty<>(this, "cropRotationGroup", null);
    private final ChangeListener<CropRotationGroupBean> cropRotationGroupIdListener = this::onCropRotationGroupIdChange;
//    private final ReadOnlyBooleanWrapper hasParentCropRotationGroupProperty = new ReadOnlyBooleanWrapper(this, "hasCropRotationGroup", 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<ICroppingPlan> beanCommentHandler;
    private final ReadOnlyStringWrapper commentTextProperty = new ReadOnlyStringWrapper(this, "commentText", "");	//	2.9.6

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

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

        saveRequiredProperty.addListener(saveRequiredListener);

        if(initialValue == null)
        {
            newItem = true;
            saveRequiredProperty.set(true);
            //	add the listeners BEFORE setting values, or default values never get sent to the builder!
            LOGGER.debug("constructor: initial value null: before addListeners");
            addListeners();
            LOGGER.debug("constructor: initial value null: before setDefaults");
            setDefaults();
            LOGGER.debug("constructor: initial value null: after setDefaults: yearOfPlan: {}", yearOfPlanProperty().getValue());
//            saveRequiredProperty.set(true);
            return;
        }

        baseItem = initialValue;

        setValues();

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

    /**
     *	Returns all CroppingPlan items wrapped as CroppingPlanBean.
     *
     *	@return	a collection of CroppingPlanBean 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<CroppingPlanBean> fetchAll() throws GNDBException
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("fetchAll()");
        ITrug server = TrugServer.getTrugServer().getTrug();
        ICroppingPlanLister gal = server.getCroppingPlanLister();
        List<CroppingPlanBean> ll = gal.fetch().stream().map(CroppingPlanBean::new).toList();
        LOGGER.traceExit();
        return FXCollections.observableArrayList(ll);
    }

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

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

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

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

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

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

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

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

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

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

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

    public Year getYearOfPlan()
    {
        return yearOfPlanProperty.get();
    }
    public void setYearOfPlan(final Year newVal)
    {
        yearOfPlanProperty.set(newVal);
    }
    /**
     *	Wraps the Date value of the CroppingPlan
     *
     *	@return	a writable property wrapping the date attribute
     */
    public ObjectProperty<Year> yearOfPlanProperty()
    {
        return yearOfPlanProperty;
    }

    private void onYearOfPlanChange(ObservableValue<? extends Year> obs, Year old, Year nval)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("onYearOfPlanChange(): old={}, new={}", old, nval);

        if (nval == null)
        {	// this is an error condition and should be flagged
            LOGGER.debug("onYearOfPlanChange(): nval is null");
            return;
        }
        if (nval.equals(old))
        {
            LOGGER.debug("onYearOfPlanChange(): nval same as old");
            return;
        }
        if (explicitSave)
        {
            LOGGER.debug("onYearOfPlanChange(): explicitSave");
            explicitBuilder.yearOfPlan(nval);
        }
        else
        {
            LOGGER.debug("onYearOfPlanChange(): NOT explicitSave");
            ITrug server = TrugServer.getTrugServer().getTrug();
            try
            {
                baseItem = server.getCroppingPlanBuilder(baseItem).yearOfPlan(nval).save();
            } catch (GNDBException ex) {
                throw new GNDBRuntimeException(ex);
            }
        }
        LOGGER.traceExit(log4jEntryMsg);
    }

    public LocationBean getLocation()
    {
        return locationProperty().getValue();
    }
    public void setLocation(final LocationBean bean)
    {
        locationProperty().setValue(bean);
    }
    public void setLocation(final ILocation item)
    {
        locationProperty().setValue(new LocationBean(item));
    }
    /**
     *	Returns the Location parent of the CroppingPlan this Bean wraps
     *
     *	@return	the Location parent of the Husbandry this Bean wraps
     */
    public ObjectProperty<LocationBean> locationProperty()
    {
        return parentLocationProperty;
    }

    /**
     *	Handle changes to the LocationId 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 onLocationIdChange(ObservableValue<? extends LocationBean> obs, LocationBean old, LocationBean nval)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("onLocationIdChange(): old={}, new={}", old, nval);

        if (nval == null)
        {	// this is an error condition and should be flagged
            LOGGER.debug("onLocationIdChange(): nval is null");
            return;
        }
        if (nval.sameAs(old))
        {
            LOGGER.debug("onLocationIdChange(): nval is sameAs old");
            return;
        }

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

        LOGGER.traceExit(log4jEntryMsg);
    }	//	onLocationIdChange()

    public CropRotationGroupBean getCropRotationGroup()
    {
        return cropRotationGroupProperty().getValue();
    }
    public void setCropRotationGroup(final CropRotationGroupBean bean)
    {
        cropRotationGroupProperty().setValue(bean);
    }
    public void setCropRotationGroup(final ICropRotationGroup item)
    {
        cropRotationGroupProperty().setValue(new CropRotationGroupBean(item));
    }

    /**
     * Returns the CropRotationGroup this PlantSpecies belongs to.
     *
     * @return	the CropRotationGroup parent of this PlantSpecies
     */
    public ObjectProperty<CropRotationGroupBean> cropRotationGroupProperty()
    {
        return parentCropRotationGroupProperty;
    }

    /**
     * Handle changes to the cropRotationGroupId 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 onCropRotationGroupIdChange(ObservableValue<? extends CropRotationGroupBean> obs, CropRotationGroupBean old, CropRotationGroupBean nval)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("onCropRotationGroupIdChange(): old={}, new={}", old, nval);

        if (nval == null)
        {	// this is an error condition and should be flagged
            LOGGER.debug("onCropRotationGroupIdChange(): nval is null");
            return;
        }
        if ( nval.sameAs(old))
        {
            LOGGER.debug("onCropRotationGroupIdChange(): nval is sameAs old");
            return;
        }

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

        LOGGER.traceExit(log4jEntryMsg);
    }

    /**
     * Must be called from the editor when the yearOfPlan, Location and CropRotationGroup are set
     *
     * @return  true    if the current settings duplacate an existing plan
     */
    public boolean checkForDuplicatePlan()
    {
        boolean duplicate = false;

        if (explicitSave)
        {
            LOGGER.debug("checkForDuplicateplan(): explicitSave");
            try
            {
                duplicate = explicitBuilder.isPlanDuplicate();
            } catch (GNDBException ex) {
                throw new GNDBRuntimeException(ex);
            }
        }
        else
        {
            LOGGER.debug("checkForDuplicatePlan(): NOT explicitSave");
            ITrug server = TrugServer.getTrugServer().getTrug();
            try
            {
                duplicate = server.getCroppingPlanBuilder(baseItem).isPlanDuplicate();
            } catch (GNDBException ex) {
                throw new GNDBRuntimeException(ex);
            }
        }
//        duplicatePlanProperty.set(duplicate);
        return duplicate;

    }

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

    /**
     * Get the CroppingActual entries for this CroppingPlan.
     *
     *	@return	A list of CroppingActual items, possibly empty
     *
     *	@throws	GNDBException	if the underlying persisted storage engine (e.g. database server) throws an exception
     *				The original error can be retrieved by <code>getCause()</code>
     */
    public ObservableList<CroppingActualBean> getCroppingActual() throws GNDBException
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("getCroppingActual()");

        childrenCroppingActual = FXCollections.observableArrayList();
        if (!newItem)
        {   //  passing a null baseItem will retrieve ALL extant CroppingActuals - which is not what we want!
            ITrug server = TrugServer.getTrugServer().getTrug();
            for (ICroppingActual ix : server.getCroppingActualLister().croppingPlan(baseItem).fetch())
            {
                childrenCroppingActual.add(new CroppingActualBean(ix));
            }
        }
        LOGGER.traceExit(log4jEntryMsg);
        return childrenCroppingActual;
    }

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

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

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

    @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 CroppingPlan
            LOGGER.debug("addComment(): NOT explicitSave");
            ITrug server = TrugServer.getTrugServer().getTrug();
            baseItem = server.getCroppingPlanBuilder(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 CroppingPlan
            LOGGER.debug("changeCommentText(): NOT explicitSave");
            ITrug server = TrugServer.getTrugServer().getTrug();
            baseItem = server.getCroppingPlanBuilder(baseItem).changeComment(comment.get().get(), text).save();
            setValues();
        }
        LOGGER.traceExit(log4jEntryMsg);
    }

    @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 CroppingPlan
            LOGGER.debug("changeCommentDate(): NOT explicitSave");
            ITrug server = TrugServer.getTrugServer().getTrug();
            baseItem = server.getCroppingPlanBuilder(baseItem).changeComment(comment.get().get(), date).save();
            setValues();
        }
        LOGGER.traceExit(log4jEntryMsg);
    }

    @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 CroppingPlan
            LOGGER.debug("deleteComment(): NOT explicitSave");
            ITrug server = TrugServer.getTrugServer().getTrug();
            baseItem = server.getCroppingPlanBuilder(baseItem).deleteComment(comment.get().get()).save();
            setValues();
        }
        LOGGER.traceExit(log4jEntryMsg);
    }

    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()
    {
        LOGGER.debug("canSave(): parentLocationProperty: {}, parentCropRotationGroupProperty: {}", parentLocationProperty.get(), parentCropRotationGroupProperty.get());
        if (!explicitSave)
            return (parentLocationProperty.get() != null) && (parentCropRotationGroupProperty.get() != null);

        return explicitBuilder.canSave();
    }

    /**
     *	Save changes to the underlying CroppingPlan 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())
        {
            return;
        }
        if (!explicitBuilder.canSave())
        {
            throw new IllegalStateException("CroppingPlanBean: cannot save at this time - mandatory values not set");
        }

        baseItem = explicitBuilder.save();
        LOGGER.debug("save(): after explicitBuilder.save(): comments: {}", ()->baseItem.getComments());
        setValues();
//        LOGGER.debug("save(): after setValues(): comments: {}", ()->beanCommentHandler.getComments());
//        LOGGER.debug("save(): after setValues(): commentTextProperty: {}", ()->beanCommentHandler.commentTextProperty());
//        childrenCroppingActual = null;
        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 CroppingPlan entry.
     *
     *	@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.getCroppingPlanBuilder(baseItem).delete();
        }
    }	//	delete()

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

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

    private void setDefaults()
    {
        saveRequiredProperty.setValue(false);
        yearOfPlanProperty.setValue(Year.now());
//        parentCropRotationGroupProperty.setValue(null);
        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);

        yearOfPlanProperty.setValue(baseItem.getYearOfPlan());
        parentLocationProperty.setValue(new LocationBean(baseItem.getLocation()));
        parentCropRotationGroupProperty.setValue(new CropRotationGroupBean(baseItem.getCropRotationGroup()));
        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()
    {
        yearOfPlanProperty.addListener(yearOfPlanListener);
        parentLocationProperty.addListener(locationIdListener);
        parentCropRotationGroupProperty.addListener(cropRotationGroupIdListener);
    }
    private void removeListeners()
    {
        yearOfPlanProperty.removeListener(yearOfPlanListener);
        parentLocationProperty.removeListener(locationIdListener);
        parentCropRotationGroupProperty.removeListener(cropRotationGroupIdListener);
    }

    private void declareBaseListeners()
    {
        // handle changes to the base item itself
        baseItemDeleted = evt -> {
            removeListeners();
            removeBaseListeners();
            baseItem = null;
            setDefaults();
        };
        baseItemReplaced = evt -> {
            if (evt.getNewValue() != null)
            {
                removeBaseListeners();
                baseItem = (ICroppingPlan) (evt.getNewValue());
                setValues();
                addBaseListeners();
            }
        };

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

    }

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

        baseItem.addPropertyChangeListener("CroppingActual", baseItemCroppingActualChanged);

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

        baseItem.removePropertyChangeListener("CroppingActual", baseItemCroppingActualChanged);

    }

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

}
