/*
 * 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
	2.0.1   Initialise cache to reduce rehashing.
            Reduce logging in processResults().
	2.2.0   Support hsqldb dialect
    2.3.0   Bug in processResults_hsqldb
    2.4.0   Support MS SQLServer
    3.0.0	Support Locations and new Quantity field
			Use DBKeyHandler
	3.1.0	Use jakarta implementation of JSON
 */

package uk.co.gardennotebook.mysql;

import uk.co.gardennotebook.spi.*;

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

import java.sql.*;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.EntryMessage;
import java.io.FileWriter;
import java.io.IOException;
import java.io.File;

import jakarta.json.JsonArrayBuilder;
import jakarta.json.JsonBuilderFactory;
import jakarta.json.JsonWriter;
import jakarta.json.JsonWriterFactory;
import jakarta.json.JsonObjectBuilder;

//import java.time.*;

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

	private final DBKeyHandler<IHusbandry> useHusbandry = new DBKeyHandler<>("husbandryId");

	private final DBKeyHandler<IAffliction> useTerminalAffliction = new DBKeyHandler<>("terminalAfflictionId");

	private final DBKeyHandler<ILocation> useLocation = new DBKeyHandler<>("locationId");

	private final DBKeyHandler<IHusbandryClass> useHusbandryClass = new DBKeyHandler<>("husbandryClassId");

	private final DBKeyHandler<IPlantSpecies> usePlantSpecies = new DBKeyHandler<>("plantSpeciesId");

	private final DBKeyHandler<IPlantVariety> usePlantVariety = new DBKeyHandler<>("plantVarietyId");

	private boolean useFromDate = false;
	private LocalDate fromDate;
	private boolean useToDate = false;
	private LocalDate toDate;

	private boolean useWhere = false;

	HusbandryLister() {}

	@Override
	public List<IHusbandry> fetch() throws GNDBException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("fetch()");

        if (MySQLCache.cacheHusbandry == null || MySQLCache.cacheHusbandry.isEmpty()) //  2.0.1
        {
            initialiseCache();
        }

        List<IHusbandry> vals = new ArrayList<>();
		boolean fetchAll = !useWhere;
        String query = "";
		switch (DBConnection.DB_IN_USE)
		{
			case MariaDB, MySQL -> query = buildSQL_MySQL();
			case hsqldb -> query = buildSQL_hsqldb();
			case MSSQLServer -> query = buildSQL_MSSQLServer();
			default -> {
				LOGGER.error("fetch(): no known rdbms");
				throw new GNDBException(new IllegalStateException("HusbandryLister: fetch(): no known RDBMS"));
			}
		}
LOGGER.debug("fetch(): query: {}", query);

		try (Connection conn = DBConnection.getConnection();
			 Statement stmt = conn.createStatement();
			 ResultSet rs = stmt.executeQuery(query);
			 )
		{
			switch (DBConnection.DB_IN_USE)
			{
				case MariaDB, MySQL -> vals = processResults_MySQL(rs);
				case hsqldb -> vals = processResults_hsqldb(rs);
				case MSSQLServer -> vals = processResults_MSSQLServer(rs);
				default -> {
					LOGGER.error("fetch(): no known rdbms");
					throw new GNDBException(new IllegalStateException("HusbandryLister: fetch(): no known RDBMS"));
				}
			}
			stmt.close();
		}catch (SQLException ex) {
			LOGGER.error("fetch(): SQLException: errorCode: {}, SQLstate: {}, message: {}", ex.getErrorCode(), ex.getSQLState(), ex.getMessage());
			throw new GNDBException(ex, ex.getErrorCode(), ex.getSQLState());
		}

		if (vals.isEmpty()) return Collections.emptyList();

		for (IHusbandry vx : vals)
		{
			MySQLCache.cacheHusbandry.putIfAbsent(vx.getKey(), vx);
		}
		if (fetchAll) { MySQLCache.completeHusbandry = true; }

		populateAffliction(vals, fetchAll);

		populatePlantSpecies(vals, fetchAll);

		populateHusbandryClass();

		populatePlantVariety(vals, fetchAll);

LOGGER.traceExit(log4jEntryMsg);
		return vals;
	}	// fetch()

    private String buildSQL_MySQL()
    {
        StringBuilder query = new StringBuilder("select d.*, c.* from husbandry as d ");
        query.append("left join (select * from comment where ownerType = 'HU') as c ");
        query.append("on d.husbandryId = c.ownerId ");
        if (useWhere) {
            useWhere = false;
            buildCommonSQL(query);
        }
        query.append(" order by d.date, d.husbandryClassId, d.plantSpeciesId, d.husbandryId, c.date");
        return query.toString();
    }   //  buildSQL_MySQL()

    private String buildSQL_hsqldb() 
    {
        StringBuilder query = new StringBuilder("select d.*, c.* from husbandry as d ");
        query.append("left join (select commentId as c_commentId, ownerId as c_ownerId, date as c_date, comment as c_comment, lastUpdated as c_lastUpdated, created as c_created from comment where ownerType = 'HU') as c ");
        query.append("on d.husbandryId = c_ownerId ");
        if (useWhere)
        {
            useWhere = false;
            buildCommonSQL(query);
        }
        query.append(" order by d.date, d.husbandryClassId, d.plantSpeciesId, d.husbandryId, c_date");
        return query.toString();
    }   //  buildSQL_hsqldb()

    private String buildSQL_MSSQLServer() 
    {
        StringBuilder query = new StringBuilder("select d.husbandryId as d_husbandryId, " +
                                                        "d.husbandryClassId as d_husbandryClassId, " +
                                                        "d.plantSpeciesId as d_plantSpeciesId, " +
                                                        "d.plantVarietyId as d_plantVarietyId, " +
                                                        "d.terminalAfflictionId as d_terminalAfflictionId, " +
														"d.locationId as d_locationId, " +
                                                        "d.date as d_date, " +
														"d.quantity as d_quantity, " +
                                                        "d.lastUpdated as d_lastUpdated, " +
                                                        "d.created as d_created," +
                                                        " c.* from husbandry as d ");
        query.append("left join (select commentId as c_commentId, ownerId as c_ownerId, date as c_date, comment as c_comment, lastUpdated as c_lastUpdated, created as c_created from comment where ownerType = 'HU') as c ");
        query.append("on d.husbandryId = c_ownerId ");
        if (useWhere)
        {
            useWhere = false;
            buildCommonSQL(query);
        }
        query.append(" order by d.date, d.husbandryClassId, d.plantSpeciesId, d.husbandryId, c_date");
        return query.toString();
    }   //  buildSQL_MSSQLServer()

    private void buildCommonSQL(StringBuilder query)
    {
        boolean first = true;
		if (useHusbandry.isUsed())
		{
			if (first) query.append(" where ");
			else query.append(" and ");
			query.append(useHusbandry.getSQLClause("d"));
			first = false;
			useHusbandry.clear();
		}

		if (useTerminalAffliction.isUsed())
		{
			if (first) query.append(" where ");
			else query.append(" and ");
			query.append(useTerminalAffliction.getSQLClause("d"));
			first = false;
			useTerminalAffliction.clear();
		}

		if (useLocation.isUsed())
		{
			if (first) query.append(" where ");
			else query.append(" and ");
			query.append(useLocation.getSQLClause("d"));
			first = false;
			useLocation.clear();
		}

		if (this.usePlantSpecies.isUsed() || this.usePlantVariety.isUsed())
        {
            if (first)
                query.append(" where ");
            else
                query.append(" and ");

			if (this.usePlantSpecies.isUsed() && this.usePlantVariety.isUsed())
				query.append(" ( ");

			if (this.usePlantSpecies.isUsed())
			{
				query.append(usePlantSpecies.getSQLClause("d"));
				first = false;
			}

			if (this.usePlantSpecies.isUsed() && this.usePlantVariety.isUsed())
				query.append(" or ");
			if (this.usePlantVariety.isUsed())
			{
				query.append(usePlantVariety.getSQLClause("d"));
				first = false;
			}
			if (this.usePlantSpecies.isUsed() && this.usePlantVariety.isUsed())
				query.append(" ) ");
			usePlantSpecies.clear();
			usePlantVariety.clear();
        }

		if (useHusbandryClass.isUsed())
		{
			if (first) query.append(" where ");
			else query.append(" and ");
			query.append(useHusbandryClass.getSQLClause("d"));
			first = false;
			useHusbandryClass.clear();
		}

        if (this.useFromDate)
        {
            if (first) query.append(" where ");
            else query.append(" and ");

            query.append(" d.date >= '").append(this.fromDate).append("'");
            first = false;
            this.useFromDate = false;
        }
        if (this.useToDate)
        {
            if (first) query.append(" where ");
            else query.append(" and ");

            query.append(" d.date <= '").append(this.toDate).append("'");
            this.useToDate = false;
        }
    }   //  buildCommonSQL()

	private List<IHusbandry> processResults_MySQL(ResultSet rs) throws SQLException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("processResults_MySQL()");

		List<IHusbandry> tempList = new ArrayList<>();

		Husbandry item = null;

		while (rs.next())
		{
			int husbandryId = rs.getInt("d.husbandryId");
			int husbandryClassId = rs.getInt("d.husbandryClassId");
			int plantSpeciesId = rs.getInt("d.plantSpeciesId");
			int tmp_plantVarietyId = rs.getInt("d.plantVarietyId");
			Integer plantVarietyId = rs.wasNull() ? null : tmp_plantVarietyId;
			int tmp_terminalAfflictionId = rs.getInt("d.terminalAfflictionId");
			Integer terminalAfflictionId = rs.wasNull() ? null : tmp_terminalAfflictionId;
			int tmp_locationId = rs.getInt("d.locationId");
			Integer locationId = rs.wasNull() ? null : tmp_locationId;
			LocalDate date = rs.getDate("date").toLocalDate();
			String quantity = rs.getString("d.quantity");
			LocalDateTime lastUpdated = rs.getTimestamp("d.lastUpdated").toLocalDateTime();
			LocalDateTime created = rs.getTimestamp("d.created").toLocalDateTime();
LOGGER.debug("husbandryId: {}, husbandryClassId: {}, plantSpeciesId: {}, plantVarietyId: {}, terminalAfflictionId: {}, locationId: {}, date: {}, quantity: {}, lastUpdated: {}, created: {}",
							husbandryId, husbandryClassId, plantSpeciesId, plantVarietyId, terminalAfflictionId, locationId, date, quantity, lastUpdated, created);   //  2.0.1
			if (item != null && husbandryId == item.getId())
			{// additional comment on the item
LOGGER.debug("processResults(): got additional comment for: {}", item);
				Comment comm = new Comment(rs.getInt("commentId"),
					rs.getInt("ownerId"),
					"HU",
					rs.getDate("c.date").toLocalDate(),
					rs.getString("c.comment"),
					rs.getTimestamp("c.lastUpdated").toLocalDateTime(),
					rs.getTimestamp("c.created").toLocalDateTime());
LOGGER.debug("processResults(): extra comment is: {}", comm);
				item = new Husbandry(item, comm);
			}
			else
			{
				if (item != null) tempList.add(item);
				int cid = rs.getInt("c.commentId");
				if (rs.wasNull())
				{// no comment
					item = new Husbandry(husbandryId, husbandryClassId, plantSpeciesId, plantVarietyId, terminalAfflictionId, locationId, date, quantity, lastUpdated, created);
				}
				else
				{// new item with comment
					Comment comm = new Comment(cid,
						husbandryId,
						"HU",
						rs.getDate("c.date").toLocalDate(),
						rs.getString("c.comment"),
						rs.getTimestamp("c.lastUpdated").toLocalDateTime(),
						rs.getTimestamp("c.created").toLocalDateTime());
LOGGER.debug("processResults(): first comment is: {}", comm);
					item = new Husbandry(husbandryId, husbandryClassId, plantSpeciesId, plantVarietyId, terminalAfflictionId, locationId, date, quantity, lastUpdated, created, comm);
				}
			}
		}
		if (item != null) tempList.add(item);

LOGGER.traceExit(log4jEntryMsg);
		return tempList;
	}	// processResults_MySQL()

	private List<IHusbandry> processResults_hsqldb(ResultSet rs) throws SQLException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("processResults_hsqldb()");

		List<IHusbandry> tempList = new ArrayList<>();

		Husbandry item = null;

		while (rs.next())
		{
			int husbandryId = rs.getInt("husbandry.husbandryId");
			int husbandryClassId = rs.getInt("husbandry.husbandryClassId");
			int plantSpeciesId = rs.getInt("husbandry.plantSpeciesId");
			int tmp_plantVarietyId = rs.getInt("husbandry.plantVarietyId");
			Integer plantVarietyId = rs.wasNull() ? null : tmp_plantVarietyId;
			int tmp_terminalAfflictionId = rs.getInt("husbandry.terminalAfflictionId");
			Integer terminalAfflictionId = rs.wasNull() ? null : tmp_terminalAfflictionId;
			int tmp_locationId = rs.getInt("husbandry.locationId");
			Integer locationId = rs.wasNull() ? null : tmp_locationId;
			LocalDate date = rs.getDate("husbandry.date").toLocalDate();
			String quantity = rs.getString("husbandry.quantity");
			LocalDateTime lastUpdated = rs.getTimestamp("husbandry.lastUpdated").toLocalDateTime();
			LocalDateTime created = rs.getTimestamp("husbandry.created").toLocalDateTime();
			LOGGER.debug("husbandryId: {}, husbandryClassId: {}, plantSpeciesId: {}, plantVarietyId: {}, terminalAfflictionId: {}, locationId: {}, date: {}, quantity: {}, lastUpdated: {}, created: {}",
					husbandryId, husbandryClassId, plantSpeciesId, plantVarietyId, terminalAfflictionId, locationId, date, quantity, lastUpdated, created);   //  2.0.1
			if (item != null && husbandryId == item.getId())
			{// additional comment on the item
LOGGER.debug("processResults(): got additional comment for: {}", item);
				Comment comm = new Comment(rs.getInt("c_commentId"),
					rs.getInt("c_ownerId"),
					"HU",
					rs.getDate("c_date").toLocalDate(),
					rs.getString("c_comment"),
					rs.getTimestamp("c_lastUpdated").toLocalDateTime(),
					rs.getTimestamp("c_created").toLocalDateTime());
LOGGER.debug("processResults(): extra comment is: {}", comm);
				item = new Husbandry(item, comm);
			}
			else
			{
				if (item != null) tempList.add(item);
				int cid = rs.getInt("c_commentId");
				if (rs.wasNull())
				{// no comment
					item = new Husbandry(husbandryId, husbandryClassId, plantSpeciesId, plantVarietyId, terminalAfflictionId, locationId, date, quantity, lastUpdated, created);
				}
				else
				{// new item with comment
					Comment comm = new Comment(cid,
						husbandryId,
						"HU",
						rs.getDate("c_date").toLocalDate(),
						rs.getString("c_comment"),
						rs.getTimestamp("c_lastUpdated").toLocalDateTime(),
						rs.getTimestamp("c_created").toLocalDateTime());
LOGGER.debug("processResults(): first comment is: {}", comm);
					item = new Husbandry(husbandryId, husbandryClassId, plantSpeciesId, plantVarietyId, terminalAfflictionId, locationId, date, quantity, lastUpdated, created, comm);
				}
			}
		}
		if (item != null) tempList.add(item);

LOGGER.traceExit(log4jEntryMsg);
		return tempList;
	}	// processResults_hsqldb()

	private List<IHusbandry> processResults_MSSQLServer(ResultSet rs) throws SQLException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("processResults_MSSQLServer()");

		List<IHusbandry> tempList = new ArrayList<>();

		Husbandry item = null;

		while (rs.next())
		{
			int husbandryId = rs.getInt("d_husbandryId");
			int husbandryClassId = rs.getInt("d_husbandryClassId");
			int plantSpeciesId = rs.getInt("d_plantSpeciesId");
			int tmp_plantVarietyId = rs.getInt("d_plantVarietyId");
			Integer plantVarietyId = rs.wasNull() ? null : tmp_plantVarietyId;
			int tmp_terminalAfflictionId = rs.getInt("d_terminalAfflictionId");
			Integer terminalAfflictionId = rs.wasNull() ? null : tmp_terminalAfflictionId;
			int tmp_locationId = rs.getInt("d_locationId");
			Integer locationId = rs.wasNull() ? null : tmp_locationId;
			LocalDate date = rs.getDate("d_date").toLocalDate();
			String quantity = rs.getString("d_quantity");
			LocalDateTime lastUpdated = rs.getTimestamp("d_lastUpdated").toLocalDateTime();
			LocalDateTime created = rs.getTimestamp("d_created").toLocalDateTime();
			LOGGER.debug("husbandryId: {}, husbandryClassId: {}, plantSpeciesId: {}, plantVarietyId: {}, terminalAfflictionId: {}, locationId: {}, date: {}, quantity: {}, lastUpdated: {}, created: {}",
					husbandryId, husbandryClassId, plantSpeciesId, plantVarietyId, terminalAfflictionId, locationId, date, quantity, lastUpdated, created);   //  2.0.1
			if (item != null && husbandryId == item.getId())
			{// additional comment on the item
LOGGER.debug("processResults(): got additional comment for: {}", item);
				Comment comm = new Comment(rs.getInt("c_commentId"),
					rs.getInt("c_ownerId"),
					"HU",
					rs.getDate("c_date").toLocalDate(),
					rs.getString("c_comment"),
					rs.getTimestamp("c_lastUpdated").toLocalDateTime(),
					rs.getTimestamp("c_created").toLocalDateTime());
LOGGER.debug("processResults(): extra comment is: {}", comm);
				item = new Husbandry(item, comm);
			}
			else
			{
				if (item != null) tempList.add(item);
				int cid = rs.getInt("c_commentId");
				if (rs.wasNull())
				{// no comment
					item = new Husbandry(husbandryId, husbandryClassId, plantSpeciesId, plantVarietyId, terminalAfflictionId, locationId, date, quantity, lastUpdated, created);
				}
				else
				{// new item with comment
					Comment comm = new Comment(cid,
						husbandryId,
						"HU",
						rs.getDate("c_date").toLocalDate(),
						rs.getString("c_comment"),
						rs.getTimestamp("c_lastUpdated").toLocalDateTime(),
						rs.getTimestamp("c_created").toLocalDateTime());
LOGGER.debug("processResults(): first comment is: {}", comm);
					item = new Husbandry(husbandryId, husbandryClassId, plantSpeciesId, plantVarietyId, terminalAfflictionId, locationId, date, quantity, lastUpdated, created, comm);
				}
			}
		}
		if (item != null) tempList.add(item);

LOGGER.traceExit(log4jEntryMsg);
		return tempList;
	}	// processResults_MSSQLServer()

	/*
	*	Populate the parents slot(s)
	*/
	private void populateAffliction(List<IHusbandry> vals, boolean fetchAll) throws GNDBException
	{
// parent table type: NL
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("populateAffliction()");

		if (fetchAll)
		{
			new AfflictionLister().fetch();
			return;
		}
		int[] keys = vals.stream().
			map(c -> ((Husbandry)c).getTerminalAfflictionId()).filter(Objects::nonNull).
			mapToInt(Integer::intValue).filter(c -> c>0).distinct().
			toArray();

		if (keys.length > 0)
		{
			new AfflictionLister().id(keys).fetch();
		}
LOGGER.traceExit(log4jEntryMsg);
	}

	private void populatePlantSpecies(List<IHusbandry> vals, boolean fetchAll) throws GNDBException
	{
// parent table type: TD
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("populatePlantSpecies()");

		if (fetchAll)
		{
			new PlantSpeciesLister().fetch();
			return;
		}
		int[] keys = vals.stream().
			mapToInt(c -> ((Husbandry)c).getPlantSpeciesId()).filter(c -> c>0).distinct().
			filter(c -> !MySQLCache.cachePlantSpecies.containsKey(c)).
			toArray();

		if (keys.length > 0)
		{
			new PlantSpeciesLister().id(keys).fetch();
		}
LOGGER.traceExit(log4jEntryMsg);
	}

	private void populateHusbandryClass() throws GNDBException
	{
// parent table type: TF
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("populateHusbandryClass()");

// just make sure everything is cached
		new HusbandryClassLister().load();
LOGGER.traceExit(log4jEntryMsg);
	}

	private void populatePlantVariety(List<IHusbandry> vals, boolean fetchAll) throws GNDBException
	{
// parent table type: NL
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("populatePlantVariety()");

		if (fetchAll)
		{
			new PlantVarietyLister().fetch();
			return;
		}
		int[] keys = vals.stream().
			map(c -> ((Husbandry)c).getPlantVarietyId()).filter(Objects::nonNull).
			mapToInt(Integer::intValue).filter(c -> c>0).distinct().
			toArray();

		if (keys.length > 0)
		{
			new PlantVarietyLister().id(keys).fetch();
		}
LOGGER.traceExit(log4jEntryMsg);
	}

	void clear()
	{
		MySQLCache.cacheHusbandry.clear();
		MySQLCache.completeHusbandry = false;
	}

	/**
	*
	*	Select only the Husbandry entries with these ids
	*	May be called multiple times to extend the list
	*
	*	@param vals	a list of ids
	*	@return	 this Lister
	*/
	HusbandryLister id(int... vals)
	{
		useHusbandry.id(vals);
		useWhere = useWhere || useHusbandry.isUsed();
		return this;
	}

	@Override
	public IHusbandryLister husbandry(IHusbandry... items)
	{
		useHusbandry.item(items);
		useWhere = useWhere || useHusbandry.isUsed();
		return this;
	}

	@Override
	public IHusbandryLister husbandry(List<IHusbandry> items)
	{
		useHusbandry.item(items);
		useWhere = useWhere || useHusbandry.isUsed();
		return this;
	}

	@Override
	public IHusbandryLister affliction(IAffliction... items)
	{
		useTerminalAffliction.item(items);
		useWhere = useWhere || useTerminalAffliction.isUsed();
		return this;
	}

	@Override
	public IHusbandryLister affliction(List<IAffliction> items)
	{
		useTerminalAffliction.item(items);
		useWhere = useWhere || useTerminalAffliction.isUsed();
		return this;
	}

	@Override
	public IHusbandryLister location(ILocation... items)
	{
		useLocation.item(items);
		useWhere = useWhere || useLocation.isUsed();
		return this;
	}

	@Override
	public IHusbandryLister location(List<ILocation> items)
	{
		useLocation.item(items);
		useWhere = useWhere || useLocation.isUsed();
		return this;
	}

	@Override
	public IHusbandryLister husbandryClass(IHusbandryClass... items)
	{
		useHusbandryClass.item(items);
		useWhere = useWhere || useHusbandryClass.isUsed();
		return this;
	}

	@Override
	public IHusbandryLister husbandryClass(List<IHusbandryClass> items)
	{
		useHusbandryClass.item(items);
		useWhere = useWhere || useHusbandryClass.isUsed();
		return this;
	}

	@Override
	public IHusbandryLister plantSpecies(IPlantSpecies... items)
	{
		usePlantSpecies.item(items);
		useWhere = useWhere || usePlantSpecies.isUsed();
		return this;
	}

	@Override
	public IHusbandryLister plantSpecies(List<IPlantSpecies> items)
	{
		usePlantSpecies.item(items);
		useWhere = useWhere || usePlantSpecies.isUsed();
		return this;
	}

	@Override
	public IHusbandryLister plantVariety(IPlantVariety... items)
	{
		usePlantVariety.item(items);
		useWhere = useWhere || usePlantVariety.isUsed();
		return this;
	}

	@Override
	public IHusbandryLister plantVariety(List<IPlantVariety> items)
	{
		usePlantVariety.item(items);
		useWhere = useWhere || usePlantVariety.isUsed();
		return this;
	}

	@Override
	public IHusbandryLister fromDate(LocalDate item)
	{
		if (item == null) return this;
		this.fromDate = item;
		this.useFromDate = true;
		this.useWhere = true;
		return this;
	}

	@Override
	public IHusbandryLister toDate(LocalDate item)
	{
		if (item == null) return this;
		this.toDate = item;
		this.useToDate = true;
		this.useWhere = true;
		return this;
	}

	void toJson(JsonBuilderFactory builderFactory, JsonWriterFactory writerFactory, File dumpDirectory) throws GNDBException
	{
		useWhere = false;
		fetch();

		JsonArrayBuilder jsonHc = builderFactory.createArrayBuilder();
		for (IHusbandry ihc : MySQLCache.cacheHusbandry.values())
		{
			Husbandry hc = (Husbandry)ihc;
			jsonHc.add(hc.toJson(builderFactory));
		}
        
        JsonObjectBuilder job = builderFactory.createObjectBuilder();
        job.add("JsonMode", "DUMP");
        job.add("JsonNBClass", "Husbandry");
        job.add("values", jsonHc);
        
		try (JsonWriter writer = writerFactory.createWriter(new FileWriter(new File(dumpDirectory, "Husbandry.json"), false)))
		{
			writer.writeObject(job.build());
		} catch (IOException ex) {
			LOGGER.error("toJson(): IOException", ex);
		}
	}	// toJson

    /**
     * The cache is likely to be large so set it up with an appropriate size rather than the default (16) to avoid rehashing
     * 
     * @since   2.0.1
     */
    private void initialiseCache() throws GNDBException
    {
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("initialiseCache()");
        if (MySQLCache.cacheHusbandry == null || MySQLCache.cacheHusbandry.isEmpty())
        {
            long recs = 0;
            try (Connection conn = DBConnection.getConnection();
				 Statement stmt = conn.createStatement();
				 ResultSet rs = stmt.executeQuery("select count(*) from husbandry");
				 )
            {
                while (rs.next())
                {
                    recs = rs.getLong(1);
                }

            }catch (SQLException ex) {
                LOGGER.error("fetch(): SQLException: errorCode: {}, SQLstate: {}, message: {}", ex.getErrorCode(), ex.getSQLState(), ex.getMessage());
                throw new GNDBException(ex, ex.getErrorCode(), ex.getSQLState());
            }
            LOGGER.debug("Husbandry table size: {}", recs);
            
            MySQLCache.cacheHusbandry = new HashMap<>((int) (recs*4/3));

        }
        LOGGER.traceExit(log4jEntryMsg);
    }

}
