/*
 * 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	Use DBKeyHandler
	3.1.0	Use jakarta implementation of JSON
 */

package uk.co.gardennotebook.mysql;

import uk.co.gardennotebook.spi.*;

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 ShoppingListLister implements IShoppingListLister
{
	private static final Logger LOGGER = LogManager.getLogger();

	private final DBKeyHandler<IShoppingList> useShoppingList = new DBKeyHandler<>("shoppingListId");

	private final DBKeyHandler<IProduct> useProduct = new DBKeyHandler<>("productId");

	private boolean useWhere = false;

	ShoppingListLister() {}

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

		List<IShoppingList> 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("ShoppingListLister: 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("ShoppingListLister: 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 (IShoppingList vx : vals)
		{
			MySQLCache.cacheShoppingList.putIfAbsent(vx.getKey(), vx);
		}
		if (fetchAll) { MySQLCache.completeShoppingList = true; }

		populateProduct(vals, fetchAll);

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

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

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

    private String buildSQL_MSSQLServer()
    {
        StringBuilder query = new StringBuilder("select d.shoppingListId as d_shoppingListId," +
                                                        "d.productId as d_productId, " +
                                                        "d.nonspecificItem as d_nonspecificItem, " +
                                                        "d.created as d_created, " +
                                                        "d.lastUpdated as d_lastUpdated, " +
                                                        " c.* from shoppinglist 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 = 'SL') as c ");
        query.append("on d.shoppingListId = c_ownerId ");
        if (useWhere)
        {
            useWhere = false;
            buildCommonSQL(query);
        }
        query.append(" order by d.shoppingListId, c_date");
        return query.toString();
    }   //  buildSQL_MSSQLServer()

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

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

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

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

		ShoppingList item = null;

		while (rs.next())
		{
			int shoppingListId = rs.getInt("d.shoppingListId");
			int tmp_productId = rs.getInt("d.productId");
			Integer productId = rs.wasNull() ? null : tmp_productId;
			String nonspecificItem = rs.getString("d.nonspecificItem");
			LocalDateTime lastUpdated = rs.getTimestamp("d.lastUpdated").toLocalDateTime();
			LocalDateTime created = rs.getTimestamp("d.created").toLocalDateTime();
LOGGER.debug("shoppingListId: {}, productId: {}, nonspecificItem: {}, lastUpdated: {}, created: {}",
                shoppingListId, productId, nonspecificItem, lastUpdated, created);
			if (item != null && shoppingListId == 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"),
					"SL",
					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 ShoppingList(item, comm);
			}
			else
			{
				if (item != null) tempList.add(item);
				int cid = rs.getInt("c.commentId");
				if (rs.wasNull())
				{// no comment
					item = new ShoppingList(shoppingListId, productId, nonspecificItem, lastUpdated, created);
				}
				else
				{// new item with comment
					Comment comm = new Comment(cid,
						shoppingListId,
						"SL",
						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 ShoppingList(shoppingListId, productId, nonspecificItem, lastUpdated, created, comm);
				}
			}
		}
		if (item != null) tempList.add(item);

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

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

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

		ShoppingList item = null;

		while (rs.next())
		{
			int shoppingListId = rs.getInt("shoppinglist.shoppingListId");
			int tmp_productId = rs.getInt("shoppinglist.productId");
			Integer productId = rs.wasNull() ? null : tmp_productId;
			String nonspecificItem = rs.getString("shoppinglist.nonspecificItem");
			LocalDateTime lastUpdated = rs.getTimestamp("shoppinglist.lastUpdated").toLocalDateTime();
			LocalDateTime created = rs.getTimestamp("shoppinglist.created").toLocalDateTime();
LOGGER.debug("shoppingListId: {}, productId: {}, nonspecificItem: {}, lastUpdated: {}, created: {}",
                shoppingListId, productId, nonspecificItem, lastUpdated, created);
			if (item != null && shoppingListId == 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"),
					"SL",
					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 ShoppingList(item, comm);
			}
			else
			{
				if (item != null) tempList.add(item);
				int cid = rs.getInt("c_commentId");
				if (rs.wasNull())
				{// no comment
					item = new ShoppingList(shoppingListId, productId, nonspecificItem, lastUpdated, created);
				}
				else
				{// new item with comment
					Comment comm = new Comment(cid,
						shoppingListId,
						"SL",
						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 ShoppingList(shoppingListId, productId, nonspecificItem, lastUpdated, created, comm);
				}
			}
		}
		if (item != null) tempList.add(item);

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

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

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

		ShoppingList item = null;

		while (rs.next())
		{
			int shoppingListId = rs.getInt("d_shoppingListId");
			int tmp_productId = rs.getInt("d_productId");
			Integer productId = rs.wasNull() ? null : tmp_productId;
			String nonspecificItem = rs.getString("d_nonspecificItem");
			LocalDateTime lastUpdated = rs.getTimestamp("d_lastUpdated").toLocalDateTime();
			LocalDateTime created = rs.getTimestamp("d_created").toLocalDateTime();
LOGGER.debug("shoppingListId: {}, productId: {}, nonspecificItem: {}, lastUpdated: {}, created: {}",
                shoppingListId, productId, nonspecificItem, lastUpdated, created);
			if (item != null && shoppingListId == 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"),
					"SL",
					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 ShoppingList(item, comm);
			}
			else
			{
				if (item != null) tempList.add(item);
				int cid = rs.getInt("c_commentId");
				if (rs.wasNull())
				{// no comment
					item = new ShoppingList(shoppingListId, productId, nonspecificItem, lastUpdated, created);
				}
				else
				{// new item with comment
					Comment comm = new Comment(cid,
						shoppingListId,
						"SL",
						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 ShoppingList(shoppingListId, productId, nonspecificItem, lastUpdated, created, comm);
				}
			}
		}
		if (item != null) tempList.add(item);

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

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

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

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

	void clear()
	{
		MySQLCache.cacheShoppingList.clear();
		MySQLCache.completeShoppingList = false;
	}

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

	@Override
	public IShoppingListLister shoppingList(IShoppingList... items)
	{
		useShoppingList.item(items);
		useWhere = useWhere || useShoppingList.isUsed();
		return this;
	}

	@Override
	public IShoppingListLister shoppingList(List<IShoppingList> items)
	{
		useShoppingList.item(items);
		useWhere = useWhere || useShoppingList.isUsed();
		return this;
	}

	@Override
	public IShoppingListLister product(IProduct... items)
	{
		useProduct.item(items);
		useWhere = useWhere || useProduct.isUsed();
		return this;
	}

	@Override
	public IShoppingListLister product(List<IProduct> items)
	{
		useProduct.item(items);
		useWhere = useWhere || useProduct.isUsed();
		return this;
	}

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

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

}
