/*
 * Copyright (C) 2018, 2019, 2021, 2023 Andrew Gegg
 *
 *	This file is part of the Garden Notebook application
 *
 * The Garden Notebook application is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/gpl.html>.
 */

/*
	Change log
    3.0.0	First version
	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 uk.co.gardennotebook.util.StoryLineTree;

import jakarta.json.JsonObject;
import java.sql.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

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

	private ICropRotationGroup oldInstance = null;

	private final boolean newInstance;

	private boolean changedAncestor = false;


	/*
	*	pest, disease or death
	*/
	private int id;
	private String name;
	private boolean changedName = 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
	*/
	CropRotationGroupBuilder()
	{
		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
	*/
	CropRotationGroupBuilder(final ICropRotationGroup 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.CROPROTATIONGROUP);
			return;
		}

		newInstance = false;
		oldInstance = oldVal;

		CropRotationGroup baseObj;
		if (oldVal instanceof CropRotationGroup)
		{
			baseObj = (CropRotationGroup)oldVal;
			this.id = baseObj.getId();
			this.name = baseObj.getName();
			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.name = oldVal.getName();
			this.description = oldVal.getDescription().orElse(null);
			this.lastUpdated = oldVal.getLastUpdated();
			this.created = oldVal.getCreated();
		}
		commentHandler = new DBCommentHandler(NotebookEntryType.CROPROTATIONGROUP, this.id);
		LOGGER.traceExit();
	}	//	constructor()

	@Override
	public boolean isNameDuplicate(final String newVal) throws GNDBException
	{
        if (newVal == null || newVal.isBlank())
            return false;
        
        if (!newInstance && !changedName)
            return false;

        if (!newInstance && newVal.equals(oldInstance.getName()))
            return false;

        new CropRotationGroupLister().load();	// ensure the cache is populated
		return MySQLCache.cacheCropRotationGroup.values().stream().anyMatch(fx -> newVal.equals(fx.getName()));
	}	// isNameDuplicate()

	@Override
	public ICropRotationGroupBuilder name(final String newVal) throws IllegalArgumentException, GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("name(): oldVal={}, newVal={}", this.name, newVal);

		if (newVal == null) return this;
		if (newVal.equals(this.name)) return this;
//		if (isNameDuplicate(newVal))
//		{
//			throw LOGGER.throwing(Level.DEBUG, new IllegalArgumentException("CropRotationGroupBuilder: name: " +newVal+" already exists"));
//		}
		this.name = newVal;
		changedName = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}

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

		if (newVal == null && this.description == null) return this;
		if (newVal != null && this.description != null && newVal.equals(this.description)) return this;
		this.description = newVal;
		changedDescription = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}

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

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

	@Override
	public ICropRotationGroupBuilder addComment(final List<String> newVals)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("addComment<list>()");

		commentHandler.addComment(newVals);
		changedComments = commentHandler.isChangedComments();
		LOGGER.traceExit("addComment");
		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
	*/
	ICropRotationGroupBuilder deleteComment(int... newVals)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("deleteComment()");

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

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

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

	@Override
	public ICropRotationGroupBuilder deleteComment(final List<IComment> vals)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("deleteComment()");

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

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

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

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

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

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

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

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

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

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

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

		// mark cache as dirty
		MySQLCache.invalidCropRotationGroup = true;
		if (!newInstance &&(somethingChanged || changedComments))
		{
			MySQLCache.cacheCropRotationGroup.remove(this.id);
		}
		// populate the cache
		new CropRotationGroupLister().id(this.id).fetch();
		ICropRotationGroup newValue = MySQLCache.cacheCropRotationGroup.get(this.id);
		if (oldInstance != null)
		{
			oldInstance.flagReplaced(newValue);
		}

		//	stop multiple saves!
		oldInstance = null;

		somethingChanged = false;
		changedComments = false;
		changedAncestor = false;
		changedName = false;
		changedDescription = false;

		LOGGER.traceExit(log4jEntryMsg);
		return newValue;
	}	//	save()

	@Override
	public boolean needSave()
	{
		return somethingChanged || changedComments || changedAncestor;
	}	// needSave()

	@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.name == null ||
			this.name.isEmpty() )
		{
			LOGGER.debug("name not set");
			return false;
		}
        
        try
        {
            if (isNameDuplicate(this.name)) 
            {
                LOGGER.debug("CropRotationGroupBuilder: canSave(): {} already exists", this.name);
                return false;
            }
        } catch (GNDBException ex) {
			throw LOGGER.throwing(Level.DEBUG, new IllegalArgumentException("CropRotationGroupBuilder: name: " +this.name+" already exists"));
        }
		return true;
	}	// canSave()

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

		if (newInstance) return LOGGER.traceExit(log4jEntryMsg, false);

		boolean  readValue = false;
		try (	Connection conn = DBConnection.getConnection();
				Statement stmt = conn.createStatement();	)
		{
            String query;
            ResultSet rs;

			switch (DBConnection.DB_IN_USE)
			{
				case MariaDB, MySQL -> query = "select exists (select 1 from plantspecies where cropRotationGroupId = " + this.id + ") as fred";
				case hsqldb -> query = "select exists (select 1 from plantspecies where cropRotationGroupId = " + this.id + ") as fred from (values(99))";
				case MSSQLServer -> query = "select CASE WHEN EXISTS (select 1 from plantspecies where cropRotationGroupId = " + this.id + ") THEN 1 ELSE 0 END as fred";
				default -> {
					LOGGER.error("canDelete(): no known rdbms");
					throw new GNDBException(new IllegalStateException("CropRotationGroupBuilder: canDelete(): no known RDBMS"));
				}
			}
LOGGER.debug("canDelete(): query: {}", query);
			rs = stmt.executeQuery(query);
            rs.next();
            readValue = rs.getBoolean("fred");
            rs.close();
LOGGER.debug("canDelete(): readValue: {}", readValue);
			if (readValue)
			{
				return LOGGER.traceExit(log4jEntryMsg, false);
			}

			switch (DBConnection.DB_IN_USE)
			{
				case MariaDB, MySQL -> query = "select exists (select 1 from croppingPlan where cropRotationGroupId = " + this.id + ") as fred";
				case hsqldb -> query = "select exists (select 1 from croppingPlan where cropRotationGroupId = " + this.id + ") as fred from (values(99))";
				case MSSQLServer -> query = "select CASE WHEN EXISTS (select 1 from croppingPlan where cropRotationGroupId = " + this.id + ") THEN 1 ELSE 0 END as fred";
				default -> {
					LOGGER.error("canDelete(): no known rdbms");
					throw new GNDBException(new IllegalStateException("CropRotationGroupBuilder: canDelete(): no known RDBMS"));
				}
			}
			LOGGER.debug("canDelete(): query: {}", query);
			rs = stmt.executeQuery(query);
			rs.next();
			readValue = rs.getBoolean("fred");
			rs.close();
			LOGGER.debug("canDelete(): readValue: {}", readValue);
			if (readValue)
			{
				return LOGGER.traceExit(log4jEntryMsg, false);
			}
			stmt.close();
		}catch (SQLException ex) {
			LOGGER.error("canDelete(): SQLException: errorCode: {}, SQLstate: {}, message: {}", ex.getErrorCode(), ex.getSQLState(), ex.getMessage());
			throw new GNDBException(ex, ex.getErrorCode(), ex.getSQLState());
		}
		return LOGGER.traceExit(log4jEntryMsg, !readValue);
	}	// canDelete()

	@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 croprotationgroup where cropRotationGroupId = " + 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 = 'AC'";
				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.cacheCropRotationGroup.remove(this.id);
		}
		oldInstance = null;
LOGGER.traceExit(log4jEntryMsg);
	}	// delete()

	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 croprotationgroup set ");
		if (changedName)
		{
			query.append("name = ?, ");
		}

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

		query.delete(query.length()-2, query.length());
		query.append(" where cropRotationGroupId = ").append(this.id);
LOGGER.debug("doUpdate(): query={} ", query.toString());
		try (	Connection conn = DBConnection.getConnection();
				PreparedStatement stmt = conn.prepareStatement(query.toString());	)
		{
			int paramIx = 1;
			if (changedName)
			{
LOGGER.debug("doUpdate(): param {}={}", paramIx, this.name);
				stmt.setString(paramIx++, this.name);
			}

			if (changedDescription)
			{
				if (this.description == null)
				{
LOGGER.debug("doUpdate(): param {} null", paramIx);
					stmt.setNull(paramIx++, java.sql.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);
	}	// 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.changedName)
		{
			throw LOGGER.throwing(Level.ERROR, new IllegalStateException("CropRotationGroupBuilder: doInsert(): name unspecified"));
		}

		StringBuilder query = new StringBuilder("insert into croprotationgroup (");
		query.append("name, ");
		if (changedDescription)
		{
			query.append("description, ");
		}

		query.replace(query.length()-2, query.length(), ") values (");
		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, this.name);
			stmt.setString(paramIx++, this.name);
			if (changedDescription) {
				if (this.description == null)
				{
LOGGER.debug("doInsert(): param {} null", paramIx);
					stmt.setNull(paramIx++, java.sql.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 CropGroupRotations 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");

		if (newVal.isEmpty())
		{
			LOGGER.debug("newVal is empty - nothing to restore");
			return;
		}

		String query = "insert into croprotationgroup (";
		query += "cropRotationGroupId, ";
		query += "subsequentCropGroupId, ";
		query += "name, ";
		query += "description, ";
		query += "lastUpdated, ";
		query += "created) ";
        if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.hsqldb)
        {
            query += " overriding system value ";
        }
        query += " values (";
		query += "?, ";
		query += "?, ";
		query += "?, ";
		query += "?, ";
		query += "?, ";
		query += "? )";
LOGGER.debug("doJsonInsert(): query={}", query);

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

			switch (DBConnection.DB_IN_USE)
			{
				case MySQL, MariaDB -> conn.createStatement().execute("SET FOREIGN_KEY_CHECKS=0;");
				case MSSQLServer -> {
					conn.createStatement().execute("SET IDENTITY_INSERT croprotationgroup ON");
					conn.createStatement().execute("ALTER TABLE croprotationgroup NOCHECK CONSTRAINT fk_CropRotationGroup_CropRotationGroup1");
				}
				case hsqldb -> conn.createStatement().execute("SET DATABASE REFERENTIAL INTEGRITY FALSE");
				default ->  {
					LOGGER.debug("fetch(): no known rdbms");
					throw new GNDBException(new IllegalStateException("no known RDBMS"));
				}
			}

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

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

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

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

//				if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
//				{
//					conn.createStatement().execute("SET IDENTITY_INSERT croprotationgroup ON");
//				}
            
            	stmt.executeUpdate();

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

				if (++txCount > 50)
				{
					conn.commit();
					txCount = 0;
				}
			}
			conn.commit();

			switch (DBConnection.DB_IN_USE)
			{
				case MySQL, MariaDB -> conn.createStatement().execute("SET FOREIGN_KEY_CHECKS=1;");
				case MSSQLServer -> {
					conn.createStatement().execute("SET IDENTITY_INSERT croprotationgroup OFF");
//					The WITH NOCHECK is important - WITH CHECK throws an error
					conn.createStatement().execute("ALTER TABLE croprotationgroup WITH NOCHECK CHECK CONSTRAINT fk_CropRotationGroup_CropRotationGroup1");
				}
				case hsqldb -> conn.createStatement().execute("SET DATABASE REFERENTIAL INTEGRITY TRUE;");
				default ->  {
					LOGGER.debug("fetch(): no known rdbms");
					throw new GNDBException(new IllegalStateException("no known RDBMS"));
				}
			}
		}catch (SQLException ex) {
			LOGGER.error("doJsonInsert(): SQLException: errorCode: {}, SQLstate: {}, message: {}", ex.getErrorCode(), ex.getSQLState(), ex.getMessage());
			throw new GNDBException(ex, ex.getErrorCode(), ex.getSQLState());
		}

LOGGER.traceExit(log4jEntryMsg);
	}	// doJsonInsert

	@Override
	public boolean hasAncestor() throws GNDBException
	{
		//	this class does not participate in story lines
		return false;
	}	//	hasAncestor()

	@Override
	public StoryLineTree<? extends INotebookEntry> getAncestors() throws GNDBException
	{
		//	this class does not participate in story lines
		return StoryLineTree.emptyTree();
	}	//	getAncestors()

	@Override
	public boolean hasDescendant() throws GNDBException
	{
		//	this class does not participate in story lines
		return false;
	}	//	hasDescendant()

	@Override
	public StoryLineTree<? extends INotebookEntry> getDescendants() throws GNDBException
	{
		//	this class does not participate in story lines
		return StoryLineTree.emptyTree();
	}	//	getDescendants()

}

