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

import fr.cenra.rhomeo.Rhomeo;
import fr.cenra.rhomeo.api.preferences.PreferenceGroup;
import fr.cenra.rhomeo.api.ui.PreferencePane;
import fr.cenra.rhomeo.core.RhomeoCore;
import fr.cenra.rhomeo.core.preferences.ftp.FTPAccess;
import fr.cenra.rhomeo.core.preferences.ftp.FTPPreferences;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.logging.Level;
import javafx.application.Platform;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.PasswordField;
import javafx.scene.control.Spinner;
import javafx.scene.control.SpinnerValueFactory;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.util.StringConverter;
import org.geotoolkit.gui.javafx.util.TaskManager;
import org.geotoolkit.internal.GeotkFX;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 *
 * @author Alexis Manin (Geomatys)
 */
@Component
@Scope("prototype")
public class FXFTPConfiguration extends BorderPane implements PreferencePane {

    @FXML
    private ComboBox<FTPPreferences.ACCESS_POINTS> uiAccess;

    @Autowired
    FTPPreferences prefs;

    @FXML
    private TextField uiURL;

    @FXML
    private Spinner<Integer> uiPort;

    @FXML
    private TextField uiDir;

    @FXML
    private TextField uiLogin;

    @FXML
    private PasswordField uiPassword;

    @FXML
    private Button uiTest;

    private FTPAccess access;

    public FXFTPConfiguration() {
        Rhomeo.loadFXML(this);
        uiPort.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0, 65535, 21, 1));
        Rhomeo.initComboBox(uiAccess, FXCollections.observableArrayList(Arrays.asList(FTPPreferences.ACCESS_POINTS.values())));
        uiAccess.setEditable(false);
        uiAccess.setConverter(new StringConverter<FTPPreferences.ACCESS_POINTS>() {
            @Override
            public String toString(FTPPreferences.ACCESS_POINTS object) {
                if (object == null)
                    return null;
                return object.getTitle();
            }

            @Override
            public FTPPreferences.ACCESS_POINTS fromString(String string) {
                if (string == null)
                    return null;
                for (final FTPPreferences.ACCESS_POINTS ap : FTPPreferences.ACCESS_POINTS.values()) {
                    if (string.equals(ap))
                        return ap;
                }

                return null;
            }
        });

        uiAccess.valueProperty().addListener(this::accessChanged);
    }

    @FXML
    void cancel(ActionEvent event) {
        if (access == null)
            clearForm();
        else
            fillFromAcccess();
    }

    @FXML
    void checkConnection(ActionEvent event) {
        final String adress = uiURL.getText();
        if (adress == null || adress.isEmpty()) {
            Rhomeo.showAlert(Alert.AlertType.WARNING, "Impossible de tester la connexion si le champs d'adresse est vide !");
        }

        final int port = uiPort.getValue();
        final String workDir = uiDir.getText();
        final String login = uiLogin.getText();
        final String pw = uiPassword.getText();

        final TaskManager.MockTask t = new TaskManager.MockTask(() -> FTPAccess.createClient(adress, port, workDir, login, pw));

        t.setOnSucceeded((evt) -> Platform.runLater(() -> {
                if (t.getValue() != null) {
                    Rhomeo.showAlert(Alert.AlertType.INFORMATION, "Connexion établie avec succès !");
                } else {
                    Rhomeo.showAlert(Alert.AlertType.WARNING, "Aucune réponse du serveur !");
                }
        }));

        t.setOnFailed(evt -> Platform.runLater(() -> GeotkFX.newExceptionDialog("Impossible de se connecter au service FTP", t.getException()).show()));

        t.runningProperty().addListener((obs, oldValue, newValue) -> uiTest.setDisable(newValue));
        TaskManager.INSTANCE.submit("Test de connexion", t);
    }

    private void accessChanged(final ObservableValue<? extends FTPPreferences.ACCESS_POINTS> obs, FTPPreferences.ACCESS_POINTS oldAccess, FTPPreferences.ACCESS_POINTS newAccess) {
        if (newAccess == null) {
            access = null;
            clearForm();

        } else {
            access = prefs.getAccess(newAccess);
            fillFromAcccess();
        }
    }

    private void clearForm() {
        uiDir.clear();
        uiLogin.clear();
        uiPassword.clear();
        uiPort.getValueFactory().setValue(21);
        uiURL.clear();
    }

    private void fillFromAcccess() {
        uiDir.setText(access.getWorkingDir());
        uiLogin.setText(access.getLogin());
        try {
            uiPassword.setText(access.getPassword());
        } catch (GeneralSecurityException ex) {
            RhomeoCore.LOGGER.log(Level.WARNING, "Cannot read password for FTP access", ex);
            Rhomeo.showAlert(Alert.AlertType.ERROR, "Impossible de lire le mot de passe enregistré");
        }
        uiPort.getValueFactory().setValue(access.getPort());
        uiURL.setText(access.getAdress());
    }

    private void fillAccess() {
        if (access == null)
            return;

        access.setPort(uiPort.getValue());
        access.setAdress(uiURL.getText());
        access.setWorkingDir(uiDir.getText());
        access.setLogin(uiLogin.getText());
        try {
            access.setPassword(uiPassword.getText());
        } catch (GeneralSecurityException ex) {
            RhomeoCore.LOGGER.log(Level.WARNING, "Cannot write password for FTP access", ex);
            GeotkFX.newExceptionDialog("Impossible d'enregistrer le mot de passe", ex).show();
        }
    }

    @Override
    public PreferenceGroup getPreferenceGroup() {
        return prefs;
    }

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

    @Override
    public void save() {
        fillAccess();
    }
}
