/*
 *
 *  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.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TableView;
import javafx.util.Callback;
import uk.co.gardennotebook.fxbean.INotebookBean;
import uk.co.gardennotebook.spi.GNDBException;

import java.util.function.Supplier;

/**
 *  A convenience class to enable adding new entries directly in TableView based Catalogues
 *
 *	@author Andy Gegg
 *	@version	3.0.4
 *	@since	3.0.1
 */
final class CatalogueNotebookBeanAdder<T extends INotebookBean> implements ChangeListener<String>
{
    private final TableView<T> tblCatalogue;
    private final Supplier<T> beanSupplier;
    private final Callback<T, ObservableValue<String>> observedProperty;

    CatalogueNotebookBeanAdder( TableView<T> tblCatalogue, Supplier<T> beanSupplier, Callback<T, ObservableValue<String>> observedProperty)
    {
        this.tblCatalogue = tblCatalogue;
        this.beanSupplier = beanSupplier;
        this.observedProperty = observedProperty;
    }

    @Override
    public void changed(ObservableValue<? extends String> observableValue, String oldVal, String newVal)
    {
        if ((newVal !=null) && !(newVal.isEmpty())) {
            if (observableValue instanceof SimpleStringProperty ssp)
            {
                T hc = (T)ssp.getBean();
                try
                {
                    hc.save();
                }
                catch (GNDBException ex)
                {
                    PanicHandler.panic(ex);
                }
                ssp.removeListener(this);

                T cb_extra = beanSupplier.get();
                observedProperty.call(cb_extra).addListener(this);
                tblCatalogue.getItems().add(cb_extra);
            }
            else
            {
                throw new RuntimeException("New CatalogueNotebookBeanAdder row not identified");
            }
        }
    }

}
