/*
 * Copyright (C) 2018, 2019, 2022, 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.3.0   Pick up tab-out from DatePicker
    2.4.0   Support tab-out on comments
    3.0.1	CommentAdder handling moved to separate class
    3.0.2	Check before Cancel if changes have been made
    		Use DateChecker::commitValue() (new in 18)
    3.0.4	Use new convenience class NotebookBeanDeleter for deletion.
    		Use new convenience class NotebookBeanCanceller to handle edit cancellation.
    		Use new convenience class EditorCommentTableHandler to handle Comment table construction.
    		Set focus on first field.
    3.1.0	Use SafeDatePicker.
 */

package uk.co.gardennotebook;

import java.io.IOException;
//import java.util.Optional;
import java.util.ResourceBundle;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
//import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
//import java.time.format.FormatStyle;

import javafx.application.Platform;
import javafx.beans.property.SimpleObjectProperty;
//import javafx.beans.value.ChangeListener;
//import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
//import javafx.scene.text.Text;
//import javafx.scene.control.Alert;
//import javafx.scene.control.ButtonType;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import uk.co.gardennotebook.fxbean.CommentBean;
import uk.co.gardennotebook.spi.GNDBException;

import javafx.scene.control.DatePicker;
import uk.co.gardennotebook.fxbean.WeatherBean;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.EntryMessage;

/**
	*	Controller class for create/update of Weather items
	*
	*	@author Andy Gegg
	*	@version	3.1.0
	*	@since	1.0
 */
final public class WeatherEditor extends GridPane implements INotebookLoadable
{

	private static final Logger LOGGER = LogManager.getLogger();

	private final WeatherBean thisValueBean;

	private Consumer<Node> loadSplit;
	private Consumer<Node> clearSplit;
	private BiConsumer<String, Node> loadTab;
	private Consumer<Node> clearTab;

	//	an observable property that the caller can monitor when a new item is being created
	private SimpleObjectProperty<WeatherBean> newBean;
	private final boolean addingItem;

	//	an observable property that the caller can monitor when an item is deleted
	private SimpleObjectProperty<Object> deletedBean;

//	private boolean addingBean;

	@FXML
	private ResourceBundle resources;

	@FXML
	private Button btnSave;
	@FXML
	private Button btnDelete;
	@FXML
	private SafeDatePicker dtpDate;
	@FXML
	private WeatherConditionCombo parentWeatherCondition;
	@FXML
	private TextField fldSeverity;

	@FXML
	private TableView<CommentBean> tbvComment;
	@FXML
	private TableColumn<CommentBean, CommentBean> tbvCommentDate;
	@FXML
	private TableColumn<CommentBean, String> tbvCommentText;

	WeatherEditor()
	{
		this(null);
	}

	WeatherEditor(WeatherBean initialVal)
	{
		this.thisValueBean = (initialVal != null ? initialVal : new WeatherBean());
		this.addingItem = (initialVal == null);
		FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/WeatherEditor.fxml"),
			ResourceBundle.getBundle("notebook") );
		fxmlLoader.setRoot(this);
		fxmlLoader.setController(this);
		try {
			fxmlLoader.load();	// NB initialize() is called from in here
		} catch (IOException exception) {
			throw new RuntimeException(exception);
		}
	}

	/*
	*	Initialises the controller class.
	*/
	@FXML
	private void initialize()
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("initialize()");

		final EditorCommentTableHandler<WeatherBean> cth = new EditorCommentTableHandler<>(resources);
		cth.constructCommentTable(tbvComment, tbvCommentDate, tbvCommentText, thisValueBean);

		thisValueBean.setSaveRequired(true);

		dtpDate.setConverter(null);	// resets to default converter
		dtpDate.valueProperty().bindBidirectional(thisValueBean.dateProperty());
		dtpDate.setMandatory();
//        //  2.3.0
//        //  if user tabs out after editing, make sure the DatePicker updates
//        dtpDate.getEditor().focusedProperty().addListener((obj, wasFocused, isFocused)->{
//            if (wasFocused && !isFocused)
//            {
//                try
//                {
////                    dtpDate.setValue(dtpDate.getConverter().fromString(dtpDate.getEditor().getText()));
//					dtpDate.commitValue();
//                } catch (DateTimeParseException e) {
//                    dtpDate.getEditor().setText(dtpDate.getConverter().toString(dtpDate.getValue()));
//                }
//            }
//        });

		parentWeatherCondition.valueProperty().bindBidirectional(thisValueBean.weatherConditionProperty());
		fldSeverity.textProperty().bindBidirectional(thisValueBean.severityProperty());
		fldSeverity.setTextFormatter(MaxLengthTextFormatter.getFormatter(255));
		btnSave.disableProperty().bind(dtpDate.valueProperty().isNull()
			.or(parentWeatherCondition.valueProperty().isNull()));
		try
		{
			btnDelete.setDisable(addingItem || !(this.thisValueBean.canDelete()));
		} catch (GNDBException ex) {
			PanicHandler.panic(ex);
		}

		Platform.runLater(() -> parentWeatherCondition.requestFocus());

		LOGGER.traceExit(log4jEntryMsg);
	}	//	initialize()

	@Override
	public void setLoadSplit(Consumer<Node> code)
	{
		loadSplit = code;
	}

	@Override
	public void setClearSplit(Consumer<Node> code)
	{
		clearSplit = code;
	}

	@Override
	public void setLoadTab(BiConsumer<String, Node> code)
	{
		loadTab = code;
	}

	@Override
	public void setClearTab(Consumer<Node> code)
	{
		clearTab = code;
	}

	@Override
	public void clearUpOnClose(Event e)
	{
		if (isCancelDenied())
		{
			e.consume();
			return;
		}

		thisValueBean.cancelEdit();
	}

	@FXML
	private void btnCancelOnAction(ActionEvent event)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("btnCancelOnAction()");
		if (thisValueBean == null)
		{
			LOGGER.debug("thisValueBean is null");
			LOGGER.traceExit(log4jEntryMsg);
			return;
		}

		if (isCancelDenied())
		{
			return;
		}

		thisValueBean.cancelEdit();
		clearTab.accept(this);
		LOGGER.traceExit(log4jEntryMsg);
	}	//	btnCancelOnAction()

	/**
	 * Check if user really wants to quit if changes have been made
	 *
	 * @return	true	user does NOT want to quit
	 */
	private boolean isCancelDenied()
	{
		if (thisValueBean.needSave())
		{
			final NotebookEditorCanceller<WeatherBean> cancelChecker = new NotebookEditorCanceller<>(resources);
			return cancelChecker.isCancelDenied(thisValueBean);
		}
		return false;
	}

	@FXML
	private void btnDeleteOnAction(ActionEvent event)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("btnDeleteOnAction()");
		if (thisValueBean == null)
		{
			LOGGER.debug("thisValueBean is null");
			LOGGER.traceExit(log4jEntryMsg);
			return;
		}

		NotebookBeanDeleter<WeatherBean> deleterImpl = new NotebookBeanDeleter<>(resources);
		if (deleterImpl.deleteItemImpl(thisValueBean))
		{
			deletedBeanProperty().setValue(new Object());
			clearTab.accept(this);
		}

		LOGGER.traceExit(log4jEntryMsg);
	}	//	btnDeleteOnAction()

	@FXML
	private void btnSaveOnAction(ActionEvent event)
	{
		EntryMessage log4jEntryMsg = LOGGER.traceEntry("btnSaveOnAction()");
		if (thisValueBean == null)
		{
			LOGGER.debug("thisValueBean is null");
			LOGGER.traceExit(log4jEntryMsg);
			return;
		}
		try
		{
			thisValueBean.save();
		} catch (GNDBException ex) {
			PanicHandler.panic(ex);
		}
		newBeanProperty().setValue(thisValueBean);
		clearTab.accept(this);
		LOGGER.traceExit(log4jEntryMsg);
	}	//	btnSaveOnAction()

	SimpleObjectProperty<WeatherBean> newBeanProperty()
	{
		if (newBean == null)
		{
			newBean = new SimpleObjectProperty<>();
		}
		return newBean;
	}

	SimpleObjectProperty<Object> deletedBeanProperty()
	{
		if (deletedBean == null)
		{
			deletedBean = new SimpleObjectProperty<>();
		}
		return deletedBean;
	}

}
