/*
 *
 *  Copyright (C) 2022 Andrew Gegg
 *
 * 	This file is part of the Gardeners Notebook application
 *
 *  The Gardeners 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>.
 *
 *
 */

package uk.co.gardennotebook;

import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import uk.co.gardennotebook.fxbean.INotebookBean;
import uk.co.gardennotebook.spi.GNDBException;

import java.util.Optional;
import java.util.ResourceBundle;

/**
 * A convenience class to handle deletion from Catalogues and in Editors
 *
 * @param resources the resource bundle containing the text of the confirmation question for the user
 * @param preDeleteAction   an Action to be carried out after the user confirms deletion but before deleting the bean.
 *                          Typically used to unbind properties (e.g. Spinners)
 *                          ()->thisValueBean.spinnerProperty().unbind()
 *
 *	@author Andy Gegg
 *	@version	3.0.4
 *	@since	3.0.4
 */
record NotebookBeanDeleter<T extends INotebookBean>(ResourceBundle resources, Action preDeleteAction)
{
    private static final Logger LOGGER = LogManager.getLogger();

    @FunctionalInterface
    interface Action
    {
        void enact();
    }

    NotebookBeanDeleter(ResourceBundle resources)
    {
        this(resources, null);
    }

    /**
     * Check the user wishes to delete then perform the deletion.
     *
     * @param ixBean The Bean holding the item selected for deletion.
     * @return true if the bean has been deleted, else false.
     */
    boolean deleteItemImpl(T ixBean)
    {
        if (ixBean == null) return false;

        if (!itemCanBeDeleted(ixBean)) return false;

        if (userConfirmsDelete())
        {
            if (preDeleteAction != null)
            {
                preDeleteAction.enact();
            }
            deleteItem(ixBean);
            return true;
        }

        return false;

    }


    /**
     * Check the item can be deleted.
     *
     * @param ixBean the item proposed for deletion.
     * @return true if the item can be deleted, else false.
     */
    private boolean itemCanBeDeleted(T ixBean)
    {
        boolean canDelete = false;
        try
        {
            canDelete = ixBean.canDelete();
        }
        catch (GNDBException ex)
        {
            PanicHandler.panic(ex);
            return false;
        }

        if (!canDelete)
        {
			LOGGER.debug("item cannot be deleted");
            Alert checkDelete = new Alert(Alert.AlertType.INFORMATION, resources.getString("alert.cannotdelete"), ButtonType.OK);
            Optional<ButtonType> result = checkDelete.showAndWait();
            return false;
        }

        return true;
    }


    /**
     * Check the user actually wants to delete the item.
     *
     * @return true if the item is indeed to be deleted, else false.
     */
    private boolean userConfirmsDelete()
    {
        Alert checkDelete = new Alert(Alert.AlertType.CONFIRMATION, resources.getString("alert.confirmdelete"), ButtonType.NO, ButtonType.YES);
        Optional<ButtonType> result = checkDelete.showAndWait();
        LOGGER.debug("after delete dialog: result:{}, result.get:{}", result, result.orElse(null));
        if (result.isPresent() && result.get() == ButtonType.YES)
        {
            LOGGER.debug("after delete confirmed");
            return true;
        }

        return false;
    }

    private void deleteItem(T ixBean)
    {
        try
        {
            ixBean.delete();
        }
        catch (GNDBException ex)
        {
            PanicHandler.panic(ex);
        }
    }
}
