/*
 * 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/>.
 */

/*
	Change log
    2.3.0   Pick up tab-out from DatePicker
    2.9.6	Disallow changes to date after today (this is silently enforced in the Persistence layer)
    3.1.0	Better date handling - short-forms, etc.  The tab-out check is no longer needed.
 */

package uk.co.gardennotebook;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.FormatStyle;
import java.util.ResourceBundle;

import javafx.scene.control.DateCell;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableCell;
import javafx.scene.layout.VBox;
import uk.co.gardennotebook.fxbean.CommentBean;

/**
	*	Implements a table cell to display/edit dates for a table of comments 
	*
	* @author Andy Gegg
	*	@version	3.1.0
	*	@since	1.0
 */
final class EditorCommentDateTableCell extends TableCell<CommentBean, CommentBean>
{
	private final ResourceBundle resources; // not actually used but retained for compatibility with EditorCommentTextTableCell
	
	EditorCommentDateTableCell(ResourceBundle res)
	{
		resources = res;
	}
	
	@Override
	protected void updateItem(CommentBean item, boolean empty) {
		super.updateItem(item, empty);
		if (item == null || empty)
		{
			setText(null);
			setGraphic(null);
			return;
		}
		dateUpdateViewMode();
	}			

	@Override
	public void startEdit() {
		super.startEdit();
		dateUpdateViewMode();
	}

	@Override
	public void cancelEdit() {
		super.cancelEdit();
		dateUpdateViewMode();
	}

	private void dateUpdateViewMode()
	{
		// protect against empty rows at end of displayed table
		if (getItem() == null) return;

		setGraphic(null);
		setText(null);
		this.setEditable(getItem().get().isPresent());
		if (isEditing())
		{
			VBox vBox = new VBox();
			final LocalDate oldDate = getItem().getDate();
			DatePicker dp = new DatePicker(getItem().getDate());
			//	2.9.6
			dp.setDayCellFactory(pk -> {
					return new DateCell() {
						@Override public void updateItem(LocalDate item, boolean empty) {
							super.updateItem(item, empty);
							if (empty || item == null)
							{
								setText(null);
								setGraphic(null);
							}
							else if (item.isAfter(LocalDate.now()))
							{
								setDisable(true);
							}
						}
					};
			});
			dp.setOnAction(ev -> {
//				if (dp.getValue() == null || dp.getValue().isAfter(LocalDate.now()))
				if (dp.getValue() == null)
				{// 2.9.6 - disallow dates after today
					dp.setValue(oldDate);
				}
				else
				{
					LocalDate date = dp.getValue();
					if (date.getYear() < 100)
						date = date.plusYears(2000);
					if (date.isAfter(LocalDate.now()))
						date = oldDate;
//					getItem().setDate(dp.getValue());
					getItem().setDate(date);
				}
				commitEdit(getItem());
			});
//          //    2.3.0
//          //    if user tabs out after editing, make sure the DatePicker updates
//            dp.getEditor().focusedProperty().addListener((obj, wasFocused, isFocused)->{
//                if (wasFocused && !isFocused)
//                {
//                    try
//                    {
//                        dp.setValue(dp.getConverter().fromString(dp.getEditor().getText()));
//                    } catch (DateTimeParseException e) {
//                        dp.getEditor().setText(dp.getConverter().toString(dp.getValue()));
//                    }
//                }
//            });
			vBox.getChildren().add(dp);
			setGraphic(vBox);
		}
		else if (getItem() != null)
		{
			setText(getItem().getDate().format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)));
		}
	}

}
