/*
 * 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.2.0   Support hsqldb dialect
    2.4.0   Support MS SQLServer
	3.0.0	Location, Quantity and Severity added
			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;

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

	private final DBKeyHandler<IAfflictionEvent> useAfflictionEvent = new DBKeyHandler<>("afflictionEventId");

	private final DBKeyHandler<IAffliction> useAffliction = new DBKeyHandler<>("afflictionId");

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

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

	private boolean forceNoPlant = false;

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

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

	private boolean useWhere = false;

	AfflictionEventLister() {}

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

		List<IAfflictionEvent> 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.debug("fetch(): no known rdbms");
				throw new GNDBException(new IllegalStateException("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.debug("fetch(): no known rdbms");
					throw new GNDBException(new IllegalStateException("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 (IAfflictionEvent vx : vals)
		{
			MySQLCache.cacheAfflictionEvent.putIfAbsent(vx.getKey(), vx);
		}
		if (fetchAll) { MySQLCache.completeAfflictionEvent = true; }

		populatePlantSpecies(vals, fetchAll);

		populateAffliction(vals, fetchAll);

		populatePlantVariety(vals, fetchAll);

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

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

    private String buildSQL_hsqldb() {
        StringBuilder query = new StringBuilder("select d.*, c.* from afflictionevent 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 = 'AE') as c ");
        query.append("on d.afflictionEventId = c_ownerId ");
        if (useWhere)
        {
            useWhere = false;
            buildCommonSQL(query);//                first = false;
        }
        query.append(" order by d.date, d.afflictionId, d.afflictionEventId, c_date");
        return query.toString();
    }   //  buildSQL_hsqldb()

    private String buildSQL_MSSQLServer() {
        StringBuilder query = new StringBuilder("select d.afflictionEventId as d_afflictionEventId, " +
                                                        "d.afflictionId as d_afflictionId, " +
														"d.plantSpeciesId as d_plantSpeciesId, " +
														"d.plantVarietyId as d_plantVarietyId, " +
														"d.locationId as d_locationId, " +
                                                        "d.date as d_date, " +
														"d.quantity as d_quantity, " +
														"d.severity as d_severity, " +
                                                        "d.lastUpdated as d_lastUpdated, " +
														"d.created as d_created, " +
                                                        " c.* from afflictionevent 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 = 'AE') as c ");
        query.append("on d.afflictionEventId = c_ownerId ");
        if (useWhere)
        {
            useWhere = false;
            buildCommonSQL(query);//                first = false;
        }
        query.append(" order by d.date, d.afflictionId, d.afflictionEventId, c_date");
        return query.toString();
    }   //  buildSQL_MSSQLServer()

    private void buildCommonSQL(StringBuilder query)
    {
        boolean first = true;

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

        if (forceNoPlant)
        {
            if (first)
                query.append(" where ");
            else
                query.append(" and ");
            
            query.append(" d.plantSpeciesId is null and d.plantVarietyId is null ");
            first = false;
        }
//        else if (this.usePlantSpeciesId || this.usePlantVarietyId)
		else 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 (useAffliction.isUsed())
		{
			if (first) query.append(" where ");
			else query.append(" and ");
			query.append(useAffliction.getSQLClause("d"));
			first = false;
			useAffliction.clear();
		}

		if (useLocation.isUsed())
		{
			if (first) query.append(" where ");
			else query.append(" and ");
			query.append(useLocation.getSQLClause("d"));
			first = false;
			useLocation.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<IAfflictionEvent> processResults_MySQL(ResultSet rs) throws SQLException
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("processResults_MySQL()");

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

		AfflictionEvent item = null;

		while (rs.next())
		{
			int afflictionEventId = rs.getInt("d.afflictionEventId");
			int afflictionId = rs.getInt("d.afflictionId");
			int tmp_plantSpeciesId = rs.getInt("d.plantSpeciesId");
			Integer plantSpeciesId = rs.wasNull() ? null : tmp_plantSpeciesId;
			int tmp_plantVarietyId = rs.getInt("d.plantVarietyId");
			Integer plantVarietyId = rs.wasNull() ? null : tmp_plantVarietyId;
			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");
			String severity = rs.getString("d.severity");
			LocalDateTime lastUpdated = rs.getTimestamp("d.lastUpdated").toLocalDateTime();
			LocalDateTime created = rs.getTimestamp("d.created").toLocalDateTime();
LOGGER.debug("afflictionEventId: {}, afflictionId: {}, plantSpeciesId: {}, plantVarietyId: {}, locationId: {}, date: {}, quantity: {}, severity: {}, lastUpdated: {}, created: {}",
                afflictionEventId, afflictionId, plantSpeciesId, plantVarietyId, locationId, date, quantity, severity, lastUpdated, created);
			if (item != null && afflictionEventId == item.getId())
			{// additional comment on the item
LOGGER.debug("processResults_MySQL(): got additional comment for: {}", item);
				Comment comm = new Comment(rs.getInt("commentId"),
					rs.getInt("ownerId"),
					"AE",
					rs.getDate("c.date").toLocalDate(),
					rs.getString("c.comment"),
					rs.getTimestamp("c.lastUpdated").toLocalDateTime(),
					rs.getTimestamp("c.created").toLocalDateTime());
LOGGER.debug("processResults_MySQL(): extra comment is: {}", comm);
				item = new AfflictionEvent(item, comm);
			}
			else
			{
				if (item != null) tempList.add(item);
				int cid = rs.getInt("c.commentId");
				if (rs.wasNull())
				{// no comment
					item = new AfflictionEvent(afflictionEventId, afflictionId, plantSpeciesId, plantVarietyId, locationId, date, quantity, severity, lastUpdated, created);
				}
				else
				{// new item with comment
					Comment comm = new Comment(cid,
						afflictionEventId,
						"AE",
						rs.getDate("c.date").toLocalDate(),
						rs.getString("c.comment"),
						rs.getTimestamp("c.lastUpdated").toLocalDateTime(),
						rs.getTimestamp("c.created").toLocalDateTime());
LOGGER.debug("processResults_MySQL(): first comment is: {}", comm);
					item = new AfflictionEvent(afflictionEventId, afflictionId, plantSpeciesId, plantVarietyId, locationId, date, quantity, severity, lastUpdated, created, comm);
				}
			}
		}
		if (item != null) tempList.add(item);

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

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

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

		AfflictionEvent item = null;

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

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

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

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

		AfflictionEvent item = null;

		while (rs.next())
		{
			int afflictionEventId = rs.getInt("d_afflictionEventId");
			int afflictionId = rs.getInt("d_afflictionId");
			int tmp_plantSpeciesId = rs.getInt("d_plantSpeciesId");
			Integer plantSpeciesId = rs.wasNull() ? null : tmp_plantSpeciesId;
			int tmp_plantVarietyId = rs.getInt("d_plantVarietyId");
			Integer plantVarietyId = rs.wasNull() ? null : tmp_plantVarietyId;
			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");
			String severity = rs.getString("d_severity");
			LocalDateTime lastUpdated = rs.getTimestamp("d_lastUpdated").toLocalDateTime();
			LocalDateTime created = rs.getTimestamp("d_created").toLocalDateTime();
LOGGER.debug("afflictionEventId: {}, afflictionId: {}, plantSpeciesId: {}, plantVarietyId: {}, locationId: {}, date: {}, quantity: {}, severity: {}, lastUpdated: {}, created: {}",
                afflictionEventId, afflictionId, plantSpeciesId, plantVarietyId, locationId, date, quantity, severity, lastUpdated, created);
			if (item != null && afflictionEventId == item.getId())
			{// additional comment on the item
LOGGER.debug("processResults_hsqldb(): got additional comment for: {}", item);
				Comment comm = new Comment(rs.getInt("c_commentId"),
					rs.getInt("c_ownerId"),
					"AE",
					rs.getDate("c_date").toLocalDate(),
					rs.getString("c_comment"),
					rs.getTimestamp("c_lastUpdated").toLocalDateTime(),
					rs.getTimestamp("c_created").toLocalDateTime());
LOGGER.debug("processResults_hsqldb(): extra comment is: {}", comm);
				item = new AfflictionEvent(item, comm);
			}
			else
			{
				if (item != null) tempList.add(item);
				int cid = rs.getInt("c_commentId");
				if (rs.wasNull())
				{// no comment
					item = new AfflictionEvent(afflictionEventId, afflictionId, plantSpeciesId, plantVarietyId, locationId, date, quantity, severity, lastUpdated, created);
				}
				else
				{// new item with comment
					Comment comm = new Comment(cid,
						afflictionEventId,
						"AE",
						rs.getDate("c_date").toLocalDate(),
						rs.getString("c_comment"),
						rs.getTimestamp("c_lastUpdated").toLocalDateTime(),
						rs.getTimestamp("c_created").toLocalDateTime());
LOGGER.debug("processResults_hsqldb(): first comment is: {}", comm);
					item = new AfflictionEvent(afflictionEventId, afflictionId, plantSpeciesId, plantVarietyId, locationId, date, quantity, severity, lastUpdated, created, comm);
				}
			}
		}
		if (item != null) tempList.add(item);

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

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

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

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

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

		if (fetchAll)
		{
			new AfflictionLister().fetch();
			return;
		}
		int[] keys = vals.stream().
			mapToInt(c -> ((AfflictionEvent)c).getAfflictionId()).filter(c -> c>0).distinct().
			filter(c -> !MySQLCache.cacheAffliction.containsKey(c)).
			toArray();

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

	private void populatePlantVariety(List<IAfflictionEvent> 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 -> ((AfflictionEvent)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.cacheAfflictionEvent.clear();
		MySQLCache.completeAfflictionEvent = false;
	}

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

	@Override
	public IAfflictionEventLister afflictionEvent(IAfflictionEvent... items)
	{
		useAfflictionEvent.item(items);
		useWhere = useWhere || useAfflictionEvent.isUsed();
		return this;
	}

	@Override
	public IAfflictionEventLister afflictionEvent(List<IAfflictionEvent> items)
	{
		useAfflictionEvent.item(items);
		useWhere = useWhere || useAfflictionEvent.isUsed();
		return this;
	}

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

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

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

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

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

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

	@Override
	public IAfflictionEventLister requireNoPlant()
	{
		forceNoPlant = true;
		useWhere = true;
		return this;
	}

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

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

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

	@Override
	public IAfflictionEventLister 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 (IAfflictionEvent ihc : MySQLCache.cacheAfflictionEvent.values())
		{
			AfflictionEvent hc = (AfflictionEvent)ihc;
			jsonHc.add(hc.toJson(builderFactory));
		}
        
        JsonObjectBuilder job = builderFactory.createObjectBuilder();
        job.add("JsonMode", "DUMP");
        job.add("JsonNBClass", "AfflictionEvent");
        job.add("values", jsonHc);
        
		try (JsonWriter writer = writerFactory.createWriter(new FileWriter(new File(dumpDirectory, "AfflictionEvent.json"), false)))
		{
			writer.writeObject(job.build());
		} catch (IOException ex) {
			LOGGER.error("toJson(): IOException", ex);
		}
	}	// toJson

}
