/*
 *
 *  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 ReviewBuilder implements IReviewBuilder
{
    private static final Logger LOGGER = LogManager.getLogger();

    private IReview oldInstance = null;

    private final boolean newInstance;

    private int id;

    private LocalDate date;
    private boolean changedDate = false;

    private Year yearInReview;
    private boolean changedYearInReview = false;

    private LocalDate coverFrom;
    private boolean changedCoverFrom = false;

    private LocalDate coverTo;
    private boolean changedCoverTo = false;

    private String title;
    private boolean changedTitle = false;

    private String description;
    private boolean changedDescription = 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
     */
    ReviewBuilder()
    {
        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
     */
    ReviewBuilder(final IReview oldVal)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("constructor(): oldVal={}", oldVal);

        if (oldVal == null || oldVal.getKey() == null)
        {
            newInstance = true;
            oldInstance = null;
            this.id = -1;
            //	need to set the default value for dates
            this.date = LocalDate.now();
            this.yearInReview = Year.now();
            commentHandler = new DBCommentHandler(NotebookEntryType.REVIEW);
            return;
        }

        newInstance = false;
        oldInstance = oldVal;

        if (oldVal instanceof Review baseObj)
        {
            this.id = baseObj.getId();
            this.date = baseObj.getDate();
            this.yearInReview = baseObj.getYearInReview();
            this.coverFrom = baseObj.getCoverFrom().orElse(null);
            this.coverTo = baseObj.getCoverTo().orElse(null);
            this.title = baseObj.getTitle();
            this.description = baseObj.getDescription().orElse(null);
            this.lastUpdated = baseObj.getLastUpdated();
            this.created = baseObj.getCreated();
        }
        else
        {
            Integer ky = oldVal.getKey();
            if (ky == null) return;
            this.id = ky;
            this.date = oldVal.getDate();
            this.yearInReview = oldVal.getYearInReview();
            this.coverFrom = oldVal.getCoverFrom().orElse(null);
            this.coverTo = oldVal.getCoverTo().orElse(null);
            this.title = oldVal.getTitle();
            this.description = oldVal.getDescription().orElse(null);
            this.lastUpdated = oldVal.getLastUpdated();
            this.created = oldVal.getCreated();
        }
        commentHandler = new DBCommentHandler(NotebookEntryType.REVIEW, this.id);

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

    @Override
    public IReviewBuilder date(LocalDate newVal)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("date(): oldVal={}, newVal={}", this.date, newVal);

        if (newVal == null) return this;
        if (newVal.equals(this.date)) return this;
        this.date = newVal;
        changedDate = true;
        somethingChanged = true;
        LOGGER.traceExit();
        return this;
    }

    @Override
    public IReviewBuilder yearInReview(Year newVal)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("yearInReview(): oldVal={}, newVal={}", this.yearInReview, newVal);

        if (newVal == null) return this;
        if (newVal.equals(this.yearInReview)) return this;
        this.yearInReview = newVal;
        changedYearInReview = true;
        somethingChanged = true;
        LOGGER.traceExit();
        return this;
    }

    @Override
    public IReviewBuilder coverFrom(LocalDate newVal)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("coverFrom(): oldVal={}, newVal={}", this.coverFrom, newVal);

        if (newVal == null && this.coverFrom == null) return this;
        if (newVal != null && newVal.equals(this.coverFrom)) return this;

        this.coverFrom = newVal;
        changedCoverFrom = true;
        somethingChanged = true;
        LOGGER.traceExit();
        return this;
    }

    @Override
    public IReviewBuilder coverTo(LocalDate newVal)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("coverTo(): oldVal={}, newVal={}", this.coverTo, newVal);

        if (newVal == null && this.coverTo == null) return this;
        if (newVal != null && newVal.equals(this.coverTo)) return this;

        this.coverTo = newVal;
        changedCoverTo = true;
        somethingChanged = true;
        LOGGER.traceExit();
        return this;
    }

    @Override
    public IReviewBuilder title(String newVal)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("title(): oldVal={}, newVal={}", this.title, newVal);

        if (newVal == null) return this;
        if (newVal.equals(this.title)) return this;

        this.title = newVal;
        changedTitle = true;
        somethingChanged = true;
        LOGGER.traceExit();
        return this;
    }

    @Override
    public IReviewBuilder description(String newVal)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("description(): oldVal={}, newVal={}", this.description, newVal);

        if (newVal == null && this.description == null) return this;
        if (newVal != null && newVal.equals(this.description)) return this;

        this.description = newVal;
        changedDescription = true;
        somethingChanged = true;
        LOGGER.traceExit();
        return this;
    }

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

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

    @Override
    public IReviewBuilder 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
     */
    IReviewBuilder deleteComment(int... newVals)
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("deleteComment()");

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

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

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

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

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

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

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

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

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

    @Override
    public IReviewBuilder 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 true;
        }

        if (this.date == null ||
            this.date == LocalDate.MAX ||
            this.date == LocalDate.MIN)
        {
            LOGGER.debug("date not set");
            return false;
        }

        if (this.title == null || this.title.isBlank())
        {
            return false;
        }

        if (this.yearInReview == null ||
                (this.yearInReview.getValue() == Year.MAX_VALUE) ||
                (this.yearInReview.getValue() == Year.MIN_VALUE) )
        {
            LOGGER.debug("Year in Review not set");
            return false;
        }

        return true;
    }	// canSave()

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

        if (coverFrom == null)
        {
            coverFrom(yearInReview.atDay(1));
        }
        if (coverTo == null)
        {
            coverTo(yearInReview.atDay(yearInReview.length()));
        }

        if (!somethingChanged && !newInstance && !changedComments)
        {
            LOGGER.traceExit("nothing changed");
            return MySQLCache.cacheReview.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.cacheReview.remove(this.id);
        }
// populate the cache
        new ReviewLister().id(this.id).fetch();
        IReview newValue = MySQLCache.cacheReview.get(this.id);
        if (oldInstance != null)
        {
            oldInstance.flagReplaced(newValue);
        }

        //	stop multiple saves!
        oldInstance = null;

        somethingChanged = false;
        changedComments = false;
        changedDate = false;
        changedYearInReview = false;
        changedCoverFrom = false;
        changedCoverTo = false;
        changedTitle = false;
        changedDescription = false;

        LOGGER.traceExit(log4jEntryMsg);
        return newValue;
    }

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

        return LOGGER.traceExit(log4jEntryMsg, !newInstance);
    }

    @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 review where reviewId = " + 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 = 'JN'";
                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.cacheReview.remove(this.id);
         }
        oldInstance = null;
        LOGGER.traceExit(log4jEntryMsg);
    }

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

        if (newInstance) return;
        if (!somethingChanged) return;

        StringBuilder query = new StringBuilder("update review set ");

        if (changedDate)
        {
            query.append("date = ?, ");
        }

        if (changedYearInReview)
        {
            query.append("yearInReview = ?, ");
        }

        if (changedCoverFrom)
        {
            query.append("coverFrom = ?, ");
        }

        if (changedCoverTo)
        {
            query.append("coverTo = ?, ");
        }

        if (changedTitle)
        {
            query.append("title = ?, ");
        }

        if (changedDescription)
        {
            query.append("description = ?, ");
        }

        query.delete(query.length()-2, query.length());
        query.append(" where reviewId = ").append(this.id);
        LOGGER.debug("doUpdate(): query={} ", query.toString());

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

            if (changedDate)
            {
                LOGGER.debug("doUpdate(): param {}={}", paramIx, Date.valueOf(this.date));
                stmt.setDate(paramIx++, Date.valueOf(this.date), java.util.Calendar.getInstance());
            }

            if (changedYearInReview)
            {
                LOGGER.debug("doUpdate(): param {}={}", paramIx, Date.valueOf(this.yearInReview.atDay(1)));
//                stmt.setDate(paramIx++, Date.valueOf(this.yearInReview.atDay(1)), java.util.Calendar.getInstance());
                if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MySQL ||
                        DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MariaDB)
                {
                    // Passing a simple Date value throws SQLException 'data truncated' (i.e. truncating 2021-01-01T00:00.00 to 2021)
                    // see https://stackoverflow.com/questions/66411364/how-to-insert-year-data-type-in-mysql-server-using-java
                    // answer from Basil Borque
                    stmt.setString(paramIx++, yearInReview.toString());
                }
                else
                {
                    stmt.setDate(paramIx++, Date.valueOf(this.yearInReview.atDay(1)), java.util.Calendar.getInstance());
                }
            }

            if (changedCoverFrom)
            {
                if (this.coverFrom == null)
                {
                    LOGGER.debug("doUpdate(): param {} null", paramIx);
                    stmt.setNull(paramIx++, Types.DATE);
                }
                else
                {
                    LOGGER.debug("doUpdate(): param {}={}", paramIx, Date.valueOf(this.coverFrom) );
                    stmt.setDate(paramIx++, Date.valueOf(this.coverFrom), java.util.Calendar.getInstance() );
                }
            }

            if (changedCoverTo)
            {
                if (this.coverTo == null)
                {
                    LOGGER.debug("doUpdate(): param {} null", paramIx);
                    stmt.setNull(paramIx++, Types.DATE);
                }
                else
                {
                    LOGGER.debug("doUpdate(): param {}={}", paramIx, Date.valueOf(this.coverTo) );
                    stmt.setDate(paramIx++, Date.valueOf(this.coverTo), java.util.Calendar.getInstance() );
                }
            }

            if (changedTitle)
            {
                    LOGGER.debug("doUpdate(): param {}={}", paramIx, this.title);
                    stmt.setString(paramIx++, this.title);
            }

            if (changedDescription)
            {
                if (this.description == null)
                {
                    LOGGER.debug("doUpdate(): param {} null", paramIx);
                    stmt.setNull(paramIx++, Types.VARCHAR);
                }
                else
                {
                    LOGGER.debug("doUpdate(): param {}={}", paramIx, this.description);
                    stmt.setString(paramIx++, this.description);
                }
            }

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

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

        StringBuilder query = new StringBuilder("insert into review (");
        query.append("date, ");
        query.append("yearInReview, ");
        query.append("title, ");

        if (changedCoverFrom)
        {
            query.append("coverFrom, ");
        }

        if (changedCoverTo)
        {
            query.append("coverTo, ");
        }

        if (changedDescription)
        {
            query.append("description, ");
        }

        query.replace(query.length()-2, query.length(), ") values (");
        query.append("?, ?, ?, "); //  date, yearInReview, title

        if (changedCoverFrom)
        {
            query.append("?, ");
        }

        if (changedCoverTo)
        {
            query.append("?, ");
        }

        if (changedDescription)
        {
            query.append("?, ");
        }

        query.replace(query.length()-2, query.length(), ")");
        LOGGER.debug("doInsert(): query={}", query.toString());

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

            LOGGER.debug("doInsert(): param {}={}", paramIx, Date.valueOf(this.date));
            stmt.setDate(paramIx++, Date.valueOf(this.date), java.util.Calendar.getInstance());

            LOGGER.debug("doInsert(): param {}={}", paramIx, Date.valueOf(this.yearInReview.atDay(1)));
//            stmt.setDate(paramIx++, Date.valueOf(this.yearInReview.atDay(1)), java.util.Calendar.getInstance());
            if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MySQL ||
                    DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MariaDB)
            {
                // Passing a simple Date value throws SQLException 'data truncated' (i.e. truncating 2021-01-01T00:00.00 to 2021)
                // see https://stackoverflow.com/questions/66411364/how-to-insert-year-data-type-in-mysql-server-using-java
                // answer from Basil Borque
                stmt.setInt(paramIx++, this.yearInReview.getValue());
            }
            else
            {
                stmt.setDate(paramIx++, Date.valueOf(this.yearInReview.atDay(1)), java.util.Calendar.getInstance());
            }

            LOGGER.debug("doInsert(): param {}={}", paramIx, this.title);
            stmt.setString(paramIx++, this.title);

            if (changedCoverFrom)
            {
                if (this.coverFrom == null)
                {
                    LOGGER.debug("doInsert(): param {} null", paramIx);
                    stmt.setNull(paramIx++, Types.DATE);
                }
                else
                {
                    LOGGER.debug("doInsert(): param {}={}", paramIx, Date.valueOf(this.coverFrom) );
                    stmt.setDate(paramIx++, Date.valueOf(this.coverFrom), java.util.Calendar.getInstance() );
                }
            }

            if (changedCoverTo)
            {
                if (this.coverTo == null)
                {
                    LOGGER.debug("doInsert(): param {} null", paramIx);
                    stmt.setNull(paramIx++, Types.DATE);
                }
                else
                {
                    LOGGER.debug("doInsert(): param {}={}", paramIx, Date.valueOf(this.coverTo) );
                    stmt.setDate(paramIx++, Date.valueOf(this.coverTo), java.util.Calendar.getInstance() );
                }
            }

            if (changedDescription) {
                if (this.description == null)
                {
                    LOGGER.debug("doInsert(): param {} null", paramIx);
                    stmt.setNull(paramIx++, Types.VARCHAR);
                }
                else
                {
                    LOGGER.debug("doInsert(): param {}={}", paramIx, this.description);
                    stmt.setString(paramIx++, this.description);
                }
            }

            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 Review 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>
     */
    void restoreJsonDump(List<JsonObject> newVal) throws GNDBException
    {
        EntryMessage log4jEntryMsg = LOGGER.traceEntry("restoreJsonDump(list JSON)");

        if (newVal.isEmpty())
            return;

        String query = "insert into review (";
        query += "reviewId, ";
        query += "date, ";
        query += "yearInReview, ";
        query += "coverFrom, ";
        query += "coverTo, ";
        query += "title, ";
        query += "description, ";
        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 review ON");
            }

            for (JsonObject jo : newVal)
            {
                if (!"DUMP".equals(jo.getString("JsonMode", "DUMP")))
                {
                    LOGGER.error("Review DUMP object is not DUMP");
                    throw new IllegalArgumentException("Review DUMP object is not DUMP");
                }
                if (!"Review".equals(jo.getString("JsonNBClass", "Review")))
                {
                    LOGGER.error("Review DUMP object is not Review");
                    throw new IllegalArgumentException("Review DUMP object is not Review");
                }
                Review ps = new Review(jo);
                if (ps.getId() <= 0)
                {//this forces the value of the id field.  The >0 test is a bodge.
                    LOGGER.error("Review DUMP object does not have an id");
                    throw new IllegalArgumentException("Review 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.getDate());
                stmt.setDate(paramIx++, Date.valueOf(ps.getDate()), java.util.Calendar.getInstance()); //  2.3.0

                LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getYearInReview());
//                stmt.setDate(paramIx++, Date.valueOf(ps.getYearInReview().atDay(1)), java.util.Calendar.getInstance()); //  2.3.0
                if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MySQL ||
                        DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MariaDB)
                {
                    // Passing a simple Date value throws SQLException 'data truncated' (i.e. truncating 2021-01-01T00:00.00 to 2021)
                    // see https://stackoverflow.com/questions/66411364/how-to-insert-year-data-type-in-mysql-server-using-java
                    // answer from Basil Borque
                    stmt.setInt(paramIx++, ps.getYearInReview().getValue());
                }
                else
                {
                    stmt.setDate(paramIx++, Date.valueOf(ps.getYearInReview().atDay(1)), java.util.Calendar.getInstance());
                }

                if (ps.getCoverFrom().isEmpty())
                {
                    LOGGER.debug("restoreJsonDump(): param {} null", paramIx);
                    stmt.setNull(paramIx++, Types.DATE);
                }
                else
                {
                    LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getCoverFrom().get());
                    stmt.setDate(paramIx++, Date.valueOf(ps.getCoverFrom().get()) );
                }

                if (ps.getCoverTo().isEmpty())
                {
                    LOGGER.debug("restoreJsonDump(): param {} null", paramIx);
                    stmt.setNull(paramIx++, Types.DATE);
                }
                else
                {
                    LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getCoverTo().get());
                    stmt.setDate(paramIx++, Date.valueOf(ps.getCoverTo().get()) );
                }

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

                if (ps.getDescription().isEmpty())
                {
                    LOGGER.debug("restoreJsonDump(): param {} null", paramIx);
                    stmt.setNull(paramIx++, Types.VARCHAR);
                }
                else
                {
                    LOGGER.debug("restoreJsonDump(): param {}={}", paramIx, ps.getDescription().get());
                    stmt.setString(paramIx++, ps.getDescription().get());
                }

                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 review OFF");
                    }
                    CommentBuilder cb = new CommentBuilder(NotebookEntryType.REVIEW, ps.getId());
                    cb.doJsonInsert(ps.getComments(), conn);
                    if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
                    {
                        conn.createStatement().execute("SET IDENTITY_INSERT review 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 review 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)

}
