/**
 * 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.Rhomeo;
import fr.cenra.rhomeo.api.InternationalResource;
import fr.cenra.rhomeo.api.data.DataContext;
import fr.cenra.rhomeo.api.result.DashboardResultItem;
import fr.cenra.rhomeo.api.result.Index;
import fr.cenra.rhomeo.core.RhomeoCore;
import fr.cenra.rhomeo.core.Session;
import fr.cenra.rhomeo.core.data.DashboardResultsManager;
import fr.cenra.rhomeo.core.result.ResultStorage;
import fr.cenra.rhomeo.core.result.ResultWriter;
import javafx.concurrent.Task;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import org.geotoolkit.gui.javafx.util.TaskManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;

import javafx.event.ActionEvent;


/**
 * @author Cédric Briançon (Geomatys)
 */
@Component("fr.cenra.rhomeo.fx.FXFinalizationPane")
@Scope("prototype")
public class FXFinalizationPane extends VBox implements InternationalResource {
    @FXML
    private Button addToDashboardBtn;

    @FXML
    private Button publishBtn;

    @Autowired
    private Session session;

    @Autowired
    private DashboardResultsManager resultsManager;

    @Autowired
    private ResultWriter resultWriter;

    @Autowired
    private ResultStorage resultStorage;

    /**
     * Stores if the results has been published or not.
     */
    private final BooleanProperty publishedProperty = new SimpleBooleanProperty(false);

    /**
     * Set to true once current results are attached to dashboard.
     */
    private final BooleanProperty onDashboardProperty = new SimpleBooleanProperty(false);

    public FXFinalizationPane() {
        Rhomeo.loadFXML(this, FXFinalizationPane.class);
    }

    /**
     * Get back to the dashboard to start a new entry of results.
     */
    @FXML
    private void newForm() {
        session.requestWorkflowStep(null);
    }

    @FXML
    private void exportResults() {
        final String initialFileName = new StringBuilder(session.getDataContext().getSite().getName())
                .append('_').append(session.getDataContext().getProtocol().getName()).append(".zip")
                .toString();

        final FileChooser.ExtensionFilter zipFilter = new FileChooser.ExtensionFilter("Archive zip", "*.zip");
        final File outputFile = Rhomeo.askOutputFilePopup(initialFileName, this, zipFilter);
        if (outputFile == null) {
            return;
        }

        TaskManager.INSTANCE.submit("Export de résultats", () -> {
            final Path outputPath = outputFile.toPath();
            Files.deleteIfExists(outputPath);
            try (final FileSystem fs = RhomeoCore.toZipFileSystem(outputPath)) {
                resultWriter.prepareWriting(fs.getRootDirectories().iterator().next())
                        .writeMetadataText()
                        .writeResults()
                        .writeAdditionalValues();
            }
            return true;
        });
    }

    /**
     * Add current results to the dashboard for the current site / protocol.
     */
    @FXML
    private void addToDashboard() {
        final Alert alert = new Alert(Alert.AlertType.CONFIRMATION,
                getFormatedResourceString("alert-add-to-dashboard"),
                ButtonType.YES, ButtonType.NO);
        alert.setResizable(true);
        final ButtonType res = alert.showAndWait().get();
        if (res == ButtonType.YES) {
            final TaskManager.MockTask task = new TaskManager.MockTask("Sauvegarde des résultats", () -> {
                resultStorage.store();
                resultsManager.addDashboardResultsItems(getResults());
                return true;
            });

            addToDashboardBtn.disableProperty().bind(task.runningProperty());

            task.setOnSucceeded(evt -> Platform.runLater(() -> {
                addToDashboardBtn.disableProperty().unbind();
                addToDashboardBtn.setDisable(true);
                onDashboardProperty.set(true);
            }));

            TaskManager.INSTANCE.submit(task);
        }
    }

    /**
     * Get current results.
     *
     * @return
     */
    private List<DashboardResultItem> getResults() {
        final List<DashboardResultItem> items = new ArrayList<>();

        final Set<Index> results = session.getResults();
        if (results != null && !results.isEmpty()) {
            final DataContext context = session.getDataContext();
            results.forEach(result -> {
                if (result.getSpi().getName().equals(result.getSpi().getIndicator().getDefaultIndex())) {
                    // Do not keep tracking point index, just results for a year.
                    items.add(new DashboardResultItem(result.getYear(), context.getSite().getName(),
                            result.getSpi().getIndicator().getName(), result.getValue() == null ? null : result.getValue().doubleValue(),
                            publishedProperty.get()));
                }
            });
        }

        return items;
    }

    @FXML
    private void publishResults(final ActionEvent evt) {
        final List<DashboardResultItem> results = getResults();
        final Task publish = publishSiteResults();
        publishBtn.disableProperty().bind(publish.runningProperty());
        publish.setOnSucceeded(event -> Platform.runLater(() -> {
            publishedProperty.set(true);
            publishBtn.disableProperty().unbind();
            publishBtn.setDisable(true);
            if (onDashboardProperty.get()) {
                TaskManager.INSTANCE.submit("Mise à jour des résultats locaux", () -> {
                    for (final DashboardResultItem item : results)
                        item.setPublished(true);
                    resultsManager.updateResults(results);
                    return true;
                });
            }
        }));

        publish.setOnFailed(event -> Platform.runLater(() -> Rhomeo.showAlert(Alert.AlertType.ERROR, "La publication des résultats a échouée !")));

        TaskManager.INSTANCE.submit(publish);
    }

    /**
     * Publish site results on the FTP.
     * Structure on the FTP is:
     * <pre>
     * results
     * |- county code
     * |--|- SHA1 geometry site
     * |--|--|- protocol
     * |--|--|--|- UUID
     * |--|--|--|--|- site.geojson
     * |--|--|--|--|- metadata.json
     * |--|--|--|--|- result.csv
     * ...
     * </pre>
     *
     * @return Publication task
     */
    private Task publishSiteResults() {
        return new TaskManager.MockTask<>("Publication de résultats", () -> {
            resultsManager.publishResults();
            return true;
        });
    }
}
