/**
 * Copyright © CENRA (2016)
 *
 * remi.clement@espaces-naturels.fr
 * 
 * This software is a multi-platform and portable application based on 
 * the scientifical toolbox to monitor wetlands. With this toolbox it’s 
 * possible to calculate indicators «RhoMéO» to monitor quality, 
 * fonctionalities and urban and agricultural pressures of wetlands. 
 * Indicators are calculated using naturalist data entered and/or imported,
 * and geographic data downloaded from a geographic server.
 * 
 * This software is governed by the CeCILL license under French law and
 * abiding by the rules of distribution of free software.  You can  use, 
 * modify and/ or redistribute the software under the terms of the CeCILL
 * license as circulated by CEA, CNRS and INRIA at the following URL
 * "http://www.cecill.info". 
 * 
 * As a counterpart to the access to the source code and  rights to copy,
 * modify and redistribute granted by the license, users are provided only
 * with a limited warranty  and the software's author,  the holder of the
 * economic rights,  and the successive licensors  have only  limited
 * liability. 
 * 
 * In this respect, the user's attention is drawn to the risks associated
 * with loading,  using,  modifying and/or developing or reproducing the
 * software by the user in light of its specific status of free software,
 * that may mean  that it is complicated to manipulate,  and  that  also
 * therefore means  that it is reserved for developers  and  experienced
 * professionals having in-depth computer knowledge. Users are therefore
 * encouraged to load and test the software's suitability as regards their
 * requirements in conditions enabling the security of their systems and/or 
 * data to be ensured and,  more generally, to use and operate it in the 
 * same conditions as regards security. 
 * 
 * The fact that you are presently reading this means that you have had
 * knowledge of the CeCILL license and that you accept its terms.
*/
package fr.cenra.rhomeo.fx;

import fr.cenra.rhomeo.api.InternationalDescription;
import fr.cenra.rhomeo.api.preferences.PasswordKey;
import fr.cenra.rhomeo.api.preferences.PreferenceGroup;
import fr.cenra.rhomeo.api.ui.PreferencePane;
import java.util.HashMap;
import java.util.Map;
import javafx.beans.property.StringProperty;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;

/**
 *
 * A default preference pane based on key/value structure.
 *
 * Each preference is displayed as a row of a {@link GridPane} in which the key
 * is displayed as a {@link Label} on the left side, and the value is displayed
 * in a {@link TextField} on the right side.
 *
 * Preferences are provided by a {@link PreferenceGroup} which must be set only
 * once.
 *
 * @author Samuel Andrés (Geomatys)
 *
 * @param <T> The TYPE of {@link PreferenceGroup} keys.
 */
public class FXDefaultPreferenceGroupPane<T extends InternationalDescription> extends GridPane implements PreferencePane<T> {

    private PreferenceGroup<T> preferenceGroup;
    private final Map<T, StringProperty> valueFields = new HashMap<>();

    /**
     * Builds a {@link FXDefaultPreferenceGroupPane} based on key/value structure of
     * a {@link PreferenceGroup}.
     *
     * @param preferenceGroup
     */
    public FXDefaultPreferenceGroupPane(final PreferenceGroup<T> preferenceGroup){
        this();
        setPreferenceGroup(preferenceGroup);
    }

    /**
     * Default constructor used by Spring to produce new prototype.
     *
     * This constructor does not fill the pane for any {@link PreferenceGroup}.
     *
     * The method {@link #setPreferenceGroup(PreferenceGroup)} must be used to fill the pane.
     */
    public FXDefaultPreferenceGroupPane(){
        final String css = FXDefaultPreferenceGroupPane.class.getResource(FXDefaultPreferenceGroupPane.class.getSimpleName()+".css").toExternalForm();
        getStylesheets().add(css);
        getStyleClass().add("pane");
    }

    @Override
    public PreferenceGroup<T> getPreferenceGroup() {
        return preferenceGroup;
    }

    /**
     * Sets the preference group.
     *
     * Must be called only once.
     *
     * If the current object has been built with the default constructor (for
     * instance by Spring autowiring), it must be called explicitly. On the
     * contrary, this method is implicitly called by the constructor using a
     * {@link PreferenceGroup} parameter.
     *
     * For each key of the {@link PreferenceGroup}, this method adds a new row
     * to the pane, with two columns. The first one contains a label relative to
     * the preference key. The second one contains a text field to edit the
     * corresponding preference value.
     *
     * @param preferenceGroup
     */
    public final void setPreferenceGroup(final PreferenceGroup<T> preferenceGroup){

        if(this.preferenceGroup!=null) throw new IllegalStateException("The preference group has already been set.");

        this.preferenceGroup = preferenceGroup;
        int row = 0;
        for(final T key : preferenceGroup.getKeys()){
            final Label label = new Label(key.getLabel());
            final String comment = key.getDescription();
            if(comment!=null && !comment.equals("")){
                label.setTooltip(new Tooltip(comment));
            }

            final Node editor = createEditor(key);
            addRow(row++, label, editor);
        }
    }

    private Node createEditor(final T key) {
        if (key instanceof PasswordKey) {
            final Button editBtn = new Button("Modifier");
            final HBox container = new HBox(5, editBtn);
            editBtn.setOnAction((evt) -> {
                final PasswordField field = new PasswordField();
                valueFields.put(key, field.textProperty());
                final Button cancelBtn = new Button("Annuler");
                cancelBtn.setCancelButton(true);
                cancelBtn.setOnAction(evt2 -> {
                    valueFields.remove(key);
                    container.getChildren().clear();
                    container.getChildren().add(editBtn);
                });
                container.getChildren().clear();
                container.getChildren().addAll(field, cancelBtn);
            });
            return container;
        } else {
            final TextField textField = new TextField(preferenceGroup.getPreference(key));
            textField.setPrefWidth(300);
            valueFields.put(key, textField.textProperty());
            return textField;
        }
    }

    /**
     * Save the preferences.
     */
    @Override
    public void save(){
        if(preferenceGroup!=null){
            for(final T key : preferenceGroup.getKeys()){
                final StringProperty value = valueFields.get(key);
                if(value!=null){
                    preferenceGroup.setPreference(key, value.getValue());
                }
            }
        }
    }

    @Override
    public Node getEditor() {
        return this;
    }
}
