package be.iminds.ilabt.jfed.util;

import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.stage.Window;
import org.controlsfx.dialog.ExceptionDialog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * JFedCommonDialogs
 */
public class JFedCommonDialogs {
    private static final Logger LOG = LoggerFactory.getLogger(JFedCommonDialogs.class);

    public static void requestEraseJFedConfiguration(Window ownerWindow) {

        Alert alert1 = new Alert(Alert.AlertType.CONFIRMATION);
        alert1.initOwner(ownerWindow);
        alert1.setContentText("Resetting jFed clears all settings and slice recovery information.\n" +
                "Do you want to proceed?");
        alert1.setTitle("WARNING: Data will be lost!");
        alert1.setHeaderText("WARNING: Data will be lost!");

        boolean shouldContinue = alert1.showAndWait().filter(response -> response == ButtonType.OK).isPresent();

        Alert alert2 = new Alert(Alert.AlertType.WARNING);
        alert2.initOwner(ownerWindow);
        alert2.setContentText("jFed will exit after resetting. Please start jFed again to continue.");
        alert2.setHeaderText("WARNING: Data will be lost!");
        alert2.setTitle("WARNING: Data will be lost!");
        alert2.getButtonTypes().setAll(ButtonType.OK, ButtonType.CANCEL);

        shouldContinue = alert2.showAndWait().filter(response -> response == ButtonType.OK).isPresent();

        if (shouldContinue) {
            //erase the preferences directory
            File jFedDir = JFedUtils.getUserDataDirectoryFile();
            if (jFedDir != null && jFedDir.exists() && jFedDir.isDirectory()) {
                try {
                    deleteFullDirectory(jFedDir);
                } catch (IOException e) {
                    LOG.warn("Error while deleting jFed dir " + jFedDir.getAbsolutePath() + " " + e.getMessage(), e);
                    ExceptionDialog dlg = new ExceptionDialog(e);
                    dlg.initOwner(ownerWindow);
                    dlg.setContentText("Error while deleting jFed dir: " + e.getMessage());
                    dlg.setTitle("Error deleting jFed directory");
                    dlg.setHeaderText("Error deleting jFed directory");

                    dlg.showAndWait();
                }
            }

            Platform.exit();
            System.exit(0);
        }

    }


    public static void deleteFullDirectory(File f) throws IOException {
        if (f.isDirectory()) {
            final File[] files = f.listFiles();
            if (files != null) {
                for (File c : files)
                    deleteFullDirectory(c);
            }
        }
        if (!f.delete())
            throw new FileNotFoundException("Failed to delete file: " + f);
    }
}
