/*
 *
 *  Copyright (C) 2021, 2023 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.1.0	Use jakarta implementation of JSON
*/

package uk.co.gardennotebook.mysql;

import org.apache.logging.log4j.Level;
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 jakarta.json.JsonObject;
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
//import java.time.Year;
import java.util.List;

/**
 *{@inheritDoc}
 *
 *	@author	Andy Gegg
 *	@version	3.1.0
 *	@since	3.0.0
 */
final class CroppingActualBuilder implements ICroppingActualBuilder
{
    private static final Logger LOGGER = LogManager.getLogger();

    private ICroppingActual oldInstance = null;

    private final boolean newInstance;

    private int id;

    private int cropppingPlanId;
    private boolean changedCropppingPlanId = false;

    private int plantSpeciesId;
    private boolean changedPlantSpeciesId = false;

    private Integer plantVarietyId;
    private boolean changedPlantVarietyId = false;

    private LocalDateTime lastUpdated;
    private LocalDateTime created;

    private boolean somethingChanged = false;

    private boolean changedComments = false;

    private DBCommentHandler commentHandler;	//	compiler will not allow declaration as final

    /**
     *	constructor to use for a new entry
     */
    CroppingActualBuilder()
    {
        this(null);
    }

    /**
     *	constructor to use to edit or delete an existing entry
     *
     *	@param	oldVal	the existing item to modify or delete; if null a new entry will be created
     */
    CroppingActualBuilder(final ICroppingActual oldVal)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("constructor(): oldVal={}", oldVal);
        if (oldVal == null || oldVal.getKey() == null || !(oldVal.getKey() instanceof Integer))
        {
            newInstance = true;
            oldInstance = null;
            this.id = -1;
            commentHandler = new DBCommentHandler(NotebookEntryType.CROPPINGPLAN);
            return;
        }

        newInstance = false;
        oldInstance = oldVal;

        if (oldVal instanceof CroppingActual baseObj)
        {
            this.id = baseObj.getId();
            this.cropppingPlanId = baseObj.getCroppingPlanId();
            this.plantSpeciesId = baseObj.getPlantSpeciesId();
            this.plantVarietyId = baseObj.getPlantVarietyId();
            this.lastUpdated = baseObj.getLastUpdated();
            this.created = baseObj.getCreated();
        }
        else
        {
            Object ky = oldVal.getKey();
            if (ky == null) return;
            this.id = (Integer)ky;
            ky = oldVal.getCroppingPlan();
            if (ky == null)
            {
                this.cropppingPlanId = 0;
            }
            else
            {
                this.cropppingPlanId = ((ICroppingPlan)ky).getKey();
            }

            ky = oldVal.getPlantSpecies();
            if (ky == null)
            {
                this.plantSpeciesId = 0;
            }
            else
            {
                this.plantSpeciesId = ((IPlantSpecies)ky).getKey();
            }

            ky = oldVal.getPlantVariety();
            if (ky == null)
            {
                this.plantVarietyId = null;
            }
            else
            {
                this.plantVarietyId = ((IPlantVariety)ky).getKey();
            }

            this.lastUpdated = oldVal.getLastUpdated();
            this.created = oldVal.getCreated();
        }
        commentHandler = new DBCommentHandler(NotebookEntryType.CROPPINGACTUAL, this.id);

        LOGGER.traceExit();
    }	//	constructor()

    /**
     *	give the (new) value of croppingPlanId
     *
     *	@param	newVal	the new value
     *	@return	this Builder
     */
    ICroppingActualBuilder croppingPlanId(final int newVal)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("croppingPlanId(): oldVal={}, newVal={}", this.cropppingPlanId, newVal);
        if (this.cropppingPlanId == newVal) return this;
        this.cropppingPlanId = newVal;
        changedCropppingPlanId = true;
        somethingChanged = true;
        LOGGER.traceExit();
        return this;
    }
    @Override
    public ICroppingActualBuilder cropppingPlan(ICroppingPlan newVal)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("cropRotationGroupId(): oldVal={}, newVal={}", this.cropppingPlanId, newVal);
        if (newVal == null) return this;
        if (this.cropppingPlanId == newVal.getKey()) return this;
        this.cropppingPlanId = newVal.getKey();
        changedCropppingPlanId = true;
        somethingChanged = true;
        LOGGER.traceExit();
        return this;
    }

    /**
     *	give the (new) value of plantSpeciesId
     *
     *	@param	newVal	the new value
     *	@return	this Builder
     */
    ICroppingActualBuilder plantSpeciesId(final int newVal)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("cropRotationGroupId(): oldVal={}, newVal={}", this.plantSpeciesId, newVal);
        if (this.plantSpeciesId == newVal) return this;
        this.plantSpeciesId = newVal;
        changedPlantSpeciesId = true;
        somethingChanged = true;
        LOGGER.traceExit();
        return this;
    }
    @Override
    public ICroppingActualBuilder plantSpecies(IPlantSpecies newVal)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("cropRotationGroupId(): oldVal={}, newVal={}", this.plantSpeciesId, newVal);
        if (newVal == null) return this;
        if (this.plantSpeciesId == newVal.getKey()) return this;
        this.plantSpeciesId = newVal.getKey();
        changedPlantSpeciesId = true;
        somethingChanged = true;
        LOGGER.traceExit();
        return this;
    }

    /**
     *	give the (new) value of plantVarietyId
     *
     *	@param	newVal	the new value
     *	@return	this Builder
     */
    ICroppingActualBuilder plantVarietyId(final int newVal)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("cropRotationGroupId(): oldVal={}, newVal={}", this.plantVarietyId, newVal);
        this.plantVarietyId = newVal;
        changedPlantVarietyId = true;
        somethingChanged = true;
        LOGGER.traceExit();
        return this;
    }
    @Override
    public ICroppingActualBuilder plantVariety(IPlantVariety newVal)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("cropRotationGroupId(): oldVal={}, newVal={}", this.plantVarietyId, newVal);
        if ((newVal == null) && (this.plantVarietyId == null)) return this;
        if ((newVal != null) && (this.plantVarietyId != null) && (this.plantVarietyId.equals(newVal.getKey()))) return this;
        if (newVal == null)
        {
            this.plantVarietyId = null;
        }
        else
        {	//	non-null value
            this.plantVarietyId = newVal.getKey();
            Integer ps_Id = newVal.getPlantSpecies().getKey();	// cannot be null
            if (!ps_Id.equals(this.plantSpeciesId))	// equals returns false if arg is null
            {
                this.plantSpeciesId = ps_Id;
                changedPlantSpeciesId = true;
            }
        }
        changedPlantVarietyId = true;
        somethingChanged = true;
        LOGGER.traceExit();
        return this;
    }

    @Override
    public ICroppingActualBuilder addComment(String... newVals)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("addComment[array]()");

        commentHandler.addComment(newVals);
        changedComments = commentHandler.isChangedComments();
        LOGGER.traceExit();
        return this;
    }

    @Override
    public ICroppingActualBuilder addComment(List<String> newVals)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("addComment[array]()");

        commentHandler.addComment(newVals);
        changedComments = commentHandler.isChangedComments();
        LOGGER.traceExit();
        return this;
    }

    /**
     *	remove a comment from this item
     *
     *	@param	newVals	the comment to remove.  If the comment does not exist, this is a null-op
     *	@return	 this Builder
     */
    ICroppingActualBuilder deleteComment(int... newVals)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("deleteComment()");

        commentHandler.deleteComment(newVals);
        changedComments = commentHandler.isChangedComments();
        LOGGER.traceExit(log4jEntryMsg);
        return this;
    }

    @Override
    public ICroppingActualBuilder deleteComment(IComment... newVals)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("deleteComment()");

        commentHandler.deleteComment(newVals);
        changedComments = commentHandler.isChangedComments();
        LOGGER.traceExit(log4jEntryMsg);
        return this;
    }

    @Override
    public ICroppingActualBuilder deleteComment(List<IComment> newVals)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("deleteComment()");

        commentHandler.deleteComment(newVals);
        changedComments = commentHandler.isChangedComments();
        LOGGER.traceExit(log4jEntryMsg);
        return this;
    }

    @Override
    public ICroppingActualBuilder changeComment(IComment base, String comment)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("changeComment()");

        commentHandler.changeComment(base, comment);
        changedComments = commentHandler.isChangedComments();
        LOGGER.traceExit(log4jEntryMsg);
        return this;
    }

    @Override
    public ICroppingActualBuilder changeComment(IComment base, LocalDate date)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("changeComment()");

        commentHandler.changeComment(base, date);
        changedComments = commentHandler.isChangedComments();
        LOGGER.traceExit(log4jEntryMsg);
        return this;
    }

    @Override
    public ICroppingActualBuilder changeComment(IComment base, LocalDate date, String comment)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("changeComment()");

        commentHandler.changeComment(base, date, comment);
        changedComments = commentHandler.isChangedComments();
        LOGGER.traceExit(log4jEntryMsg);
        return this;
    }

    @Override
    public boolean needSave()
    {
        LOGGER.debug("needSave: somethingChanged : {}, changedComments: {}", somethingChanged, changedComments);
        return somethingChanged || changedComments;
    }

    @Override
    public boolean canSave()
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("canSave(): newInstance={}", newInstance);

        if (!needSave())
        {//	save() will be a null-op but that's OK
            return !newInstance;
        }

        if (this.cropppingPlanId <= 0)
        {
            LOGGER.debug("canSave: Cropping Plan not set, CroppingActual: planId: {}, plantSpeciesId: {}, plantVarietyId: {}", cropppingPlanId, plantSpeciesId, plantVarietyId);
//            System.out.println("Cropping Plan not set");
            return false;
        }

        if (this.plantSpeciesId <= 0)
        {
            LOGGER.debug("Plant species not set");
//            System.out.println("Plant species not set");
            return false;
        }

        return true;
    }

    @Override
    public boolean canDelete() throws GNDBException
    {
        return true;
    }

    @Override
    public void delete() throws GNDBException
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("delete(): newInstance={}", newInstance);

        if (newInstance) return;
        if (!canDelete()) return;

        int res = 0;
        String query = "delete from croppingactual where croppingActualId = " + this.id;
        LOGGER.debug("delete(): query: {}", query);
        try (Connection conn = DBConnection.getConnection();
             Statement stmt = conn.createStatement();	)
        {
            res = stmt.executeUpdate(query);
            LOGGER.debug("delete(): result: {}", res);
            // tidy up dependencies with nullable keys
            if (res > 0) {
                query = "delete from comment where ownerId = " + this.id + " and ownerType = '"+NotebookEntryType.CROPPINGACTUAL.type()+"'";
                int res2 = stmt.executeUpdate(query);
                LOGGER.debug("delete() comments: result: {}", res2);
            }
            stmt.close();
        }catch (SQLException ex) {
            LOGGER.error("delete(): SQLException: errorCode: {}, SQLstate: {}, message: {}", ex.getErrorCode(), ex.getSQLState(), ex.getMessage());
            throw new GNDBException(ex, ex.getErrorCode(), ex.getSQLState());
        }
        if (res > 0)
        {
            oldInstance.flagDeleted();
            MySQLCache.cacheCroppingPlan.remove(this.id);
            //	tell any parent beans the child list has mutated
            //	only additions and deletions matter, other changes will be reflected through the child bean
            MySQLCache.cacheCroppingPlan.get(oldInstance.getCroppingPlan().getKey()).flagChildDeleted(oldInstance);
        }
        oldInstance = null;
        LOGGER.traceExit(log4jEntryMsg);
    }

    @Override
    public ICroppingActual save() throws GNDBException
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("save(): somethingChanged: {}, newInstance: {}, changedComments: {}",
                somethingChanged, newInstance, changedComments);

        if (!somethingChanged && !newInstance && !changedComments)
        {
            LOGGER.traceExit("nothing changed");
            return MySQLCache.cacheCroppingActual.get(this.id);
        }

        if (newInstance)
        {
            doInsert();
        }
        else if (somethingChanged)
        {
            doUpdate();
        }

        if (changedComments)
        {
            commentHandler.setParentId(this.id);
            commentHandler.save();
        }

// mark cache as dirty
        if (!newInstance &&(somethingChanged || changedComments))
        {
            MySQLCache.cacheCroppingActual.remove(this.id);
        }
// populate the cache
        new CroppingActualLister().id(this.id).fetch();
        ICroppingActual newValue = MySQLCache.cacheCroppingActual.get(this.id);
//System.out.println("newValue: "+newValue);
        if (oldInstance != null)
        {
            oldInstance.flagReplaced(newValue);
        }

        //	tell any parent beans the child list has mutated
        //	only additions and deletions matter, other changes will be reflected through the child bean
        if (newInstance)
        {
//            System.out.println("cropRotationGroupId: "+cropRotationGroupId);
            MySQLCache.cacheCroppingPlan.get(cropppingPlanId).flagChildAdded(newValue);
        }
        else
        {	//	updated
            if (changedCropppingPlanId)
            {
                if (oldInstance != null)
                {
                    MySQLCache.cacheCroppingPlan.get(oldInstance.getCroppingPlan().getKey()).flagChildDeleted(oldInstance);
                }
                MySQLCache.cacheCroppingPlan.get(newValue.getCroppingPlan().getKey()).flagChildAdded(newValue);
            }
            if (changedPlantSpeciesId)
            {
                if (oldInstance != null)
                {
                    MySQLCache.cachePlantSpecies.get(oldInstance.getPlantSpecies().getKey()).flagChildDeleted(oldInstance);
                }
                MySQLCache.cachePlantSpecies.get(newValue.getPlantSpecies().getKey()).flagChildAdded(newValue);
            }
            if (changedPlantVarietyId)
            {
                if (oldInstance != null)
                {
                    oldInstance.getPlantVariety().ifPresent(item -> MySQLCache.cachePlantVariety.get(item.getKey()).flagChildDeleted(oldInstance) );
                }
                newValue.getPlantVariety().ifPresent(item -> MySQLCache.cachePlantVariety.get(item.getKey()).flagChildAdded(newValue) );
            }
        }

        //	stop multiple saves!
        oldInstance = null;

        somethingChanged = false;
        changedComments = false;
        changedCropppingPlanId = false;
        changedPlantSpeciesId = false;
        changedPlantVarietyId = false;

        LOGGER.traceExit(log4jEntryMsg);
        return newValue;
    }

    private void doUpdate() throws GNDBException
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("doUpdate(): newInstance={}, somethingChanged={}", newInstance, somethingChanged);

        if (newInstance) return;
        if (!somethingChanged) return;
        String query = "update croppingactual set ";
        if (changedCropppingPlanId)
        {
            query += "cropropppingPlanId = ?, ";
        }

        if (changedPlantSpeciesId)
        {
            query += "plantSpeciesId = ?, ";
        }

        if (changedPlantVarietyId)
        {
            query += "planVarietyId = ?, ";
        }

        query = query.substring(0, query.length() - 2);
        query += " where croppingActualId = " + this.id;
        LOGGER.debug("doUpdate(): query={} ", query);

        try (Connection conn = DBConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query);)
        {
            int paramIx = 1;
            if (changedCropppingPlanId)
            {
                LOGGER.debug("doUpdate(): param {}={}", paramIx, this.changedCropppingPlanId);
                stmt.setInt(paramIx++, this.cropppingPlanId);
            }

            if (changedPlantSpeciesId)
            {
                LOGGER.debug("doUpdate(): param {}={}", paramIx, this.plantSpeciesId);
                stmt.setInt(paramIx++, this.plantSpeciesId);
            }

            if (changedPlantVarietyId)
            {
                if (this.plantVarietyId == null)
                {
                    LOGGER.debug("doUpdate(): param {} null", paramIx);
                    stmt.setNull(paramIx++, java.sql.Types.INTEGER);
                }
                else
                {
                    LOGGER.debug("doUpdate(): param {}={}", paramIx, this.plantVarietyId);
                    stmt.setInt(paramIx++, this.plantVarietyId);
                }
            }

            stmt.executeUpdate();

        }catch (SQLException ex) {
            LOGGER.error("doUpdate(): SQLException: errorCode: {}, SQLstate: {}, message: {}", ex.getErrorCode(), ex.getSQLState(), ex.getMessage());
            throw new GNDBException(ex, ex.getErrorCode(), ex.getSQLState());
        }
        LOGGER.traceExit(log4jEntryMsg);
    }   //  doUpdate()

    private void doInsert() throws GNDBException
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("doInsert(): newInstance={}", newInstance);

        if (!newInstance) return;
        if (!canSave())
        {
            throw LOGGER.throwing(Level.ERROR, new IllegalStateException("doInsert(): save criteria not met"));
        }

        if (!this.changedCropppingPlanId)
        {
            throw LOGGER.throwing(Level.ERROR, new IllegalStateException("CroppingActualBuilder: doInsert(): Cropping Plan unspecified"));
        }
        if (!this.changedPlantSpeciesId)
        {
            throw LOGGER.throwing(Level.ERROR, new IllegalStateException("CroppingActualBuilder: doInsert(): Plant Species unspecified"));
        }

        String query = "insert into croppingactual ";
        query += "(croppingPlanId, plantSpeciesId";
        if (changedPlantVarietyId)
        {
            query += ", plantVarietyId";
        }
        query += ") values (?, ?";
        if (changedPlantVarietyId)
        {
            query += ", ?";
        }
        query += ");";
//        System.out.println("query: "+ query);
        LOGGER.debug("doInsert(): query={}", query);

        try (	Connection conn = DBConnection.getConnection();
                 PreparedStatement stmt = conn.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS); )
        {
            int paramIx = 1;

            LOGGER.debug("doInsert(): param {}={}", paramIx, this.cropppingPlanId);
            stmt.setInt(paramIx++, this.cropppingPlanId);
            LOGGER.debug("doInsert(): param {}={}", paramIx, this.plantSpeciesId);
            stmt.setInt(paramIx++, this.plantSpeciesId);

            if (changedPlantVarietyId) {
                if (this.plantVarietyId == null)
                {
                    LOGGER.debug("doInsert(): param {} null", paramIx);
                    stmt.setNull(paramIx++, java.sql.Types.INTEGER);
                }
                else
                {
                    LOGGER.debug("doInsert(): param {}={}", paramIx, this.plantVarietyId);
                    stmt.setInt(paramIx++, this.plantVarietyId);
                }
            }

            stmt.executeUpdate();

            ResultSet rs = stmt.getGeneratedKeys();
            rs.next();
            int newId = rs.getInt(1);
            LOGGER.debug("doInsert(): newId: {}", newId);
            this.id = newId;
        }
        catch (SQLException ex) {
            LOGGER.error("doInsert(): SQLException: errorCode: {}, SQLstate: {}, message: {}", ex.getErrorCode(), ex.getSQLState(), ex.getMessage());
            throw new GNDBException(ex, ex.getErrorCode(), ex.getSQLState());
        }

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

    /**
     * Process the whole JSON array from a DUMP
     *
     *  @param newVal    a list of JSON objects representing Husbandry entries as output by a JSON DUMP
     *  @throws	GNDBException	If the underlying MySQL database throws SQLException it is translated to this.
     *				The causal SQLException can be retrieved by <code>getCause()</code>
     *
     * @since 2.2.5
     */
    void restoreJsonDump(List<JsonObject> newVal) throws GNDBException
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("restoreJsonDump(list JSON)");

        if (newVal.isEmpty())
            return;

        String query = "insert into croppingactual (";
        query += "croppingActualId, ";
        query += "croppingPlanId, ";
        query += "plantSpeciesId, ";
        query += "plantVarietyId, ";
        query += "lastUpdated, ";
        query += "created) ";
        if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.hsqldb)
        {
            query += " overriding system value ";
        }
        query += " values (?, ?, ?, ?, ?, ?)";
        LOGGER.debug("restoreJsonDump(): query={}", query.toString());

        try (	Connection conn = DBConnection.getConnection();
                 PreparedStatement stmt = conn.prepareStatement(query.toString());	)
        {
            conn.setAutoCommit(false);
            int txCount = 0;
            if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
            {
                conn.createStatement().execute("SET IDENTITY_INSERT croppingactual ON");
            }

            for (JsonObject jo : newVal)
            {
                if (!"DUMP".equals(jo.getString("JsonMode", "DUMP")))
                {
                    LOGGER.error("CroppingActual DUMP object is not DUMP");
                    throw new IllegalArgumentException("CroppingActual DUMP object is not DUMP");
                }
                if (!"CroppingActual".equals(jo.getString("JsonNBClass", "Husbandry")))
                {
                    LOGGER.error("CroppingActual DUMP object is not CroppingActual");
                    throw new IllegalArgumentException("CroppingActual DUMP object is not CroppingActual");
                }
                CroppingActual ps = new CroppingActual(jo);
                if (ps.getId() <= 0)
                {//this forces the value of the id field.  The >0 test is a bodge.
                    LOGGER.error("CroppingActual DUMP object does not have an id");
                    throw new IllegalArgumentException("CroppingActual DUMP object does not have an id");
                }
                int paramIx = 1;
                LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getId());
                stmt.setInt(paramIx++, ps.getId());

                LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getCroppingPlanId());
                stmt.setInt(paramIx++, ps.getCroppingPlanId());

                LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getPlantSpeciesId());
                stmt.setInt(paramIx++, ps.getPlantSpeciesId());

                if (ps.getPlantVarietyId() == null)
                {
                    LOGGER.debug("restoreJsonDump(): param {} null", paramIx);
                    stmt.setNull(paramIx++, java.sql.Types.INTEGER);
                }
                else
                {
                    LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getPlantVarietyId());
                    stmt.setInt(paramIx++, ps.getPlantVarietyId());
                }

                LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getLastUpdated());
                stmt.setTimestamp(paramIx++, Timestamp.valueOf(ps.getLastUpdated()));
                LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getCreated());
                stmt.setTimestamp(paramIx++, Timestamp.valueOf(ps.getCreated()));

                stmt.executeUpdate();

                if (!ps.getComments().isEmpty())
                {
                    if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
                    {
                        conn.createStatement().execute("SET IDENTITY_INSERT croppingactual OFF");
                    }
                    CommentBuilder cb = new CommentBuilder(NotebookEntryType.HUSBANDRY, ps.getId());
                    cb.doJsonInsert(ps.getComments(), conn);
                    if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
                    {
                        conn.createStatement().execute("SET IDENTITY_INSERT croppingactual ON");
                    }
                }

                if (++txCount > 50)
                {
                    conn.commit();
                    txCount = 0;
                }
            }
            conn.commit();
            if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
            {
                conn.createStatement().execute("SET IDENTITY_INSERT croppingactual OFF");
            }

        }catch (SQLException ex) {
        LOGGER.error("restoreJsonDump(): SQLException: errorCode: {}, SQLstate: {}, message: {}", ex.getErrorCode(), ex.getSQLState(), ex.getMessage());
        throw new GNDBException(ex, ex.getErrorCode(), ex.getSQLState());
        }
    }	// restoreJsonDump(JsonObjects)
}
