/*
 * Copyright (C) 2018, 2019, 2021 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
	2.2.0   Support hsqldb dialect
    2.3.0   Retrieve generated keys properly!
    2.4.0   Support MS SQLServer
    3.0.0	Use DBCommentHandler
 */

package uk.co.gardennotebook.mysql;

import uk.co.gardennotebook.spi.*;

import uk.co.gardennotebook.util.StoryLineTree;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.EntryMessage;
import org.apache.logging.log4j.Level;

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

	private IRetailer oldInstance = null;

	private final boolean newInstance;

	private boolean changedAncestor = false;

	private int id;
	private String name;
	private boolean changedName = false;
	private String description;
	private boolean changedDescription = false;
	private String address;
	private boolean changedAddress = false;
	private String webSite;
	private boolean changedWebSite = false;
	private String eMail;
	private boolean changedEMail = false;
	private String phone;
	private boolean changedPhone = false;
	private String mobile;
	private boolean changedMobile = false;

	/*
	*	If true, this retailer ONLY supplies Products of their own brand
	*/
	private boolean ownBrandOnly = false;
	private boolean changedOwnBrandOnly = 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
	*/
	RetailerBuilder()
	{
		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
	*/
	RetailerBuilder(final IRetailer 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.RETAILER);
			return;
		}

		newInstance = false;
		oldInstance = oldVal;

		Retailer baseObj;
		if (oldVal instanceof Retailer)
		{
			baseObj = (Retailer)oldVal;
			this.id = baseObj.getId();
			this.name = baseObj.getName();
			this.description = baseObj.getDescription().orElse(null);
			this.address = baseObj.getAddress().orElse(null);
			this.webSite = baseObj.getWebSite().orElse(null);
			this.eMail = baseObj.getEMail().orElse(null);
			this.phone = baseObj.getPhone().orElse(null);
			this.mobile = baseObj.getMobile().orElse(null);
			this.ownBrandOnly = baseObj.isOwnBrandOnly();
			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.address = oldVal.getAddress().orElse(null);
			this.webSite = oldVal.getWebSite().orElse(null);
			this.eMail = oldVal.getEMail().orElse(null);
			this.phone = oldVal.getPhone().orElse(null);
			this.mobile = oldVal.getMobile().orElse(null);
			this.ownBrandOnly = oldVal.isOwnBrandOnly();
			this.lastUpdated = oldVal.getLastUpdated();
			this.created = oldVal.getCreated();
		}
		commentHandler = new DBCommentHandler(NotebookEntryType.RETAILER, this.id);
		LOGGER.traceExit();
	}	//	constructor()

	@Override
	public boolean isNameDuplicate(final String newVal) throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("isNameDuplicate({})", newVal);

        if (newVal == null || newVal.isBlank())
            return false;
        
        if (!newInstance && !changedName)
            return false;

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

		boolean duplicateFound = false;
		String query;
		switch (DBConnection.DB_IN_USE)
		{
			case MariaDB, MySQL -> query = "select exists (select 1 from retailer where name = ? ) as numvals";
			case hsqldb -> query = "select exists (select 1 from retailer where name = ? ) as numvals from (values(99))";
			case MSSQLServer -> query = "select CASE WHEN EXISTS (select 1 from retailer where name = ? ) THEN 1 ELSE 0 END as numvals";
			default -> {
				LOGGER.error("isNameDuplicate(): no known rdbms");
				throw new GNDBException(new IllegalStateException("RetailerBuilder: isNameDuplicate(): no known RDBMS"));
			}
		}
LOGGER.debug("isNameDuplicate(): query: {}", query);
		try (	Connection conn = DBConnection.getConnection();
				PreparedStatement stmt = conn.prepareStatement(query);	)
		{
			stmt.setString(1, newVal);
			ResultSet rs = stmt.executeQuery();
            rs.next();
            duplicateFound = rs.getBoolean("numvals");
LOGGER.debug("isNameDuplicate(): result: {}", duplicateFound);
			stmt.close();
		}catch (SQLException ex) {
			LOGGER.error("isNameDuplicate(): SQLException: errorCode: {}, SQLstate: {}, message: {}", ex.getErrorCode(), ex.getSQLState(), ex.getMessage());
			throw new GNDBException(ex, ex.getErrorCode(), ex.getSQLState());
		}
		return LOGGER.traceExit(log4jEntryMsg, duplicateFound);
	}	// isNameDuplicate()

	@Override
	public IRetailerBuilder 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;
		this.name = newVal;
		changedName = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}

	@Override
	public IRetailerBuilder 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 IRetailerBuilder address(final String newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("address(): oldVal={}, newVal={}", this.address, newVal);

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

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

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

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

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

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

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

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

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

	@Override
	public IRetailerBuilder ownBrandOnly(final boolean newVal)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("ownBrandOnly(): oldVal={}, newVal={}", this.ownBrandOnly, newVal);

		if (!(newVal ^ this.ownBrandOnly)) return this;	// ^ is exclusive or
		this.ownBrandOnly = newVal;
		changedOwnBrandOnly = true;
		somethingChanged = true;
		LOGGER.traceExit();
		return this;
	}

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

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

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

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

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

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

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

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

	@Override
	public IRetailerBuilder 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 IRetailerBuilder 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 IRetailerBuilder 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 IRetailer 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.cacheRetailer.get(this.id);
		}

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

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

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

		//	stop multiple saves!
		oldInstance = null;

		somethingChanged = false;
		changedComments = false;
		changedAncestor = false;
		changedName = false;
		changedDescription = false;
		changedAddress = false;
		changedWebSite = false;
		changedEMail = false;
		changedPhone = false;
		changedMobile = false;
		changedOwnBrandOnly = 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("RetailerBuilder: canSave(): {} already exists", this.name);
                return false;
            }
        } catch (GNDBException ex) {
			throw LOGGER.throwing(Level.DEBUG, new IllegalArgumentException("PlantSpeciesBuilder: commonName: " +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 productbrand where ownBrandRetailerId = " + this.id + ") as fred";
				case hsqldb -> query = "select exists (select 1 from productbrand where ownBrandRetailerId = " + this.id + ") as fred from (values(99))";
				case MSSQLServer -> query = "select CASE WHEN EXISTS (select 1 from productbrand where ownBrandRetailerId = " + this.id + ") THEN 1 ELSE 0 END as fred";
				default -> {
					LOGGER.error("canDelete(): no known rdbms");
					throw new GNDBException(new IllegalStateException("RetailerBuilder: 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 purchase where retailerId = " + this.id + ") as fred";
				case hsqldb -> query = "select exists (select 1 from purchase where retailerId = " + this.id + ") as fred from (values(99))";
				case MSSQLServer -> query = "select CASE WHEN EXISTS (select 1 from purchase where retailerId = " + this.id + ") THEN 1 ELSE 0 END as fred";
				default -> {
					LOGGER.error("canDelete(): no known rdbms");
					throw new GNDBException(new IllegalStateException("RetailerBuilder: canDelete(): no known RDBMS"));
				}
			}
LOGGER.debug("canDelete(): query: {}", query);
			rs = stmt.executeQuery(query);
            rs.next();
            readValue = 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 retailerhasproduct where retailerId = " + this.id + ") as fred";
				case hsqldb -> query = "select exists (select 1 from retailerhasproduct where retailerId = " + this.id + ") as fred from (values(99))";
				case MSSQLServer -> query = "select CASE WHEN EXISTS (select 1 from retailerhasproduct where retailerId = " + this.id + ") THEN 1 ELSE 0 END as fred";
				default -> {
					LOGGER.error("canDelete(): no known rdbms");
					throw new GNDBException(new IllegalStateException("RetailerBuilder: canDelete(): no known RDBMS"));
				}
			}
LOGGER.debug("canDelete(): query: {}", query);
			rs = stmt.executeQuery(query);
            rs.next();
            readValue = 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 retailer where retailerId = " + 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 = 'SU'";
				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.cacheRetailer.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 retailer set ");
		if (changedName)
		{
			query.append("name = ?, ");
		}

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

		if (changedAddress)
		{
			query.append("address = ?, ");
		}

		if (changedWebSite)
		{
			query.append("webSite = ?, ");
		}

		if (changedEMail)
		{
			query.append("eMail = ?, ");
		}

		if (changedPhone)
		{
			query.append("phone = ?, ");
		}

		if (changedMobile)
		{
			query.append("mobile = ?, ");
		}

		if (changedOwnBrandOnly)
		{
			query.append("ownBrandOnly = ?, ");
		}

		query.delete(query.length()-2, query.length());
		query.append(" where retailerId = ").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);
				}
			}

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

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

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

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

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

			if (changedOwnBrandOnly)
			{
LOGGER.debug("doUpdate(): param {}={}", paramIx, this.ownBrandOnly);
				stmt.setBoolean(paramIx++, this.ownBrandOnly);
			}

			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("RetailerBuilder: doInsert(): name unspecified"));
		}

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

		if (changedAddress)
		{
			query.append("address, ");
		}

		if (changedWebSite)
		{
			query.append("webSite, ");
		}

		if (changedEMail)
		{
			query.append("eMail, ");
		}

		if (changedPhone)
		{
			query.append("phone, ");
		}

		if (changedMobile)
		{
			query.append("mobile, ");
		}

		query.replace(query.length()-2, query.length(), ") values (");
		query.append("?, ");
		query.append("?, ");
		if (changedDescription)
		{
			query.append("?, ");
		}

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

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

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

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

		if (changedMobile)
		{
			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);
LOGGER.debug("doInsert(): param {}={}", paramIx, this.ownBrandOnly);
			stmt.setBoolean(paramIx++, this.ownBrandOnly);
			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);
				}
			}

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

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

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

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

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

			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

	/**
	*	Used to restore a table from a JSON dump.
	*	The RetailerBuilder(oldVal) constructor MUST be used with a Retailer object created using its JSON constructor.
	*	All fields (including timestamps) are written to the database, no checks are made.
	*
	*	@param	newVal	A Retailer object created from a JSON object written as a 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 doJsonInsert(Retailer newVal) throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("doJsonInsert(): newVal={}", newVal);

		int currId = newVal.getId();
		StringBuilder query = new StringBuilder("insert into retailer (");
		if (newVal.getId() > 0)
		{//this forces the value of the id field.  The >0 test is a bodge.
			query.append("retailerId, ");
		}
		query.append("name, ");
		query.append("description, ");
		query.append("address, ");
		query.append("webSite, ");
		query.append("eMail, ");
		query.append("phone, ");
		query.append("mobile, ");
		query.append("ownBrandOnly, ");
		query.append("lastUpdated, ");
		query.append("created, ");
		query.replace(query.length() - 2, query.length(), ")");
        if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.hsqldb && newVal.getId() > 0)
        {
            query.append(" overriding system value ");
        }
        query.append(" values (");
		if (newVal.getId() > 0)
		{//this forces the value of the id field.  The >0 test is a bodge.
			query.append(newVal.getId()).append(", ");
		}
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.append("?, ");
		query.replace(query.length()-2, query.length(), ")");
LOGGER.debug("doJsonInsert(): query={}", query.toString());

		try (	Connection conn = DBConnection.getConnection();
				PreparedStatement stmt = conn.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS); )
		{
			int paramIx = 1;
LOGGER.debug("doJsonInsert(): param {}={}", paramIx, newVal.getName());
			stmt.setString(paramIx++, newVal.getName());
			if (newVal.getDescription().isEmpty())
			{
LOGGER.debug("doJsonInsert(): param {} null", paramIx);
				stmt.setNull(paramIx++, java.sql.Types.VARCHAR);
			}
			else
			{
LOGGER.debug("doJsonInsert(): param {}={}", paramIx, newVal.getDescription().get());
				stmt.setString(paramIx++, newVal.getDescription().get());
			}

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

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

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

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

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

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

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

			if (currId <= 0)
			{
                ResultSet rs = stmt.getGeneratedKeys();
				rs.next();
				currId = rs.getInt(1);
LOGGER.debug("doJsonInsert(): currId: {}", currId);
			}

            if (DBConnection.DB_IN_USE == DBConnection.RDBMS_ENUM.MSSQLServer )
            {
                conn.createStatement().execute("SET IDENTITY_INSERT retailer OFF");
            }

            if (!newVal.getComments().isEmpty())
            {
                CommentBuilder cb = new CommentBuilder(NotebookEntryType.RETAILER, currId);
                cb.doJsonInsert(newVal.getComments(), conn);
            }
		}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 IRetailerBuilder ancestor(IPurchaseItem ancestor) throws GNDBException
	{
		return this;
	}	//	ancestor(PurchaseItem)

	@Override
	public IRetailerBuilder ancestor(IGroundwork ancestor) throws GNDBException
	{
		return this;
	}	//	ancestor(Groundwork)

	@Override
	public IRetailerBuilder ancestor(IAfflictionEvent ancestor) throws GNDBException
	{
		return this;
	}	//	ancestor(AfflictionEvent)

	@Override
	public IRetailerBuilder ancestor(IHusbandry ancestor) throws GNDBException
	{
		return this;
	}	//	ancestor(Husbandry)

	@Override
	public IRetailerBuilder ancestor(ISaleItem ancestor) throws GNDBException
	{
		return this;
	}	//	ancestor(SaleItem)

	@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()

	@Override
	public boolean addDescendant(IPurchaseItem descendant) throws GNDBException
	{
		return false;
	}	//	addDescendant(PurchaseItem)

	@Override
	public boolean addDescendant(IGroundwork descendant) throws GNDBException
	{
		return false;
	}	//	addDescendant(Groundwork)

	@Override
	public boolean addDescendant(IAfflictionEvent descendant) throws GNDBException
	{
		return false;
	}	//	addDescendant(AfflictionEvent)

	@Override
	public boolean addDescendant(IHusbandry descendant) throws GNDBException
	{
		return false;
	}	//	addDescendant(Husbandry)

	@Override
	public boolean addDescendant(ISaleItem descendant) throws GNDBException
	{
		return false;
	}	//	addDescendant(SaleItem)

}

