package nl.guno.intellij.savechangelisttopatches.settings;

import java.io.File;

import javax.swing.*;

import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Comparing;
import nl.guno.intellij.savechangelisttopatches.MessageResources;

public class SettingsPanel {
    private Settings mySettings;

    private JPanel rootComponent;
    private JTextField saveLocationField;
    private JCheckBox saveOnCloseField;
    private JButton directoryButton;

    SettingsPanel(Settings settings) {
        mySettings = settings;
        reset();
        directoryButton.addActionListener(e -> {
            String currentFileLocation = saveLocationField.getText();
            JFileChooser folderChooser = new JFileChooser(currentFileLocation);
            folderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int returnVal = folderChooser.showDialog(rootComponent, MessageResources.message("configuration.folderChooser.approveButton.text"));
            if ((returnVal == 0) && (new File(folderChooser.getSelectedFile().getPath()).canWrite()))
                saveLocationField.setText(folderChooser.getSelectedFile().getPath());
        });
    }

    void reset() {
        saveLocationField.setText(mySettings.getSaveLocation());
        saveOnCloseField.setSelected(mySettings.getSaveOnClose());
    }

    boolean isModified() {
        return !Comparing.equal(mySettings.getSaveLocation(), saveLocationField.getText().trim())
                || mySettings.getSaveOnClose() != saveOnCloseField.isSelected();
    }

    void apply() {
        final String saveLocation = saveLocationField.getText().trim();
        if (new File(saveLocation).canWrite()) {
            mySettings.setSaveLocation(saveLocation);
            mySettings.setSaveOnClose(saveOnCloseField.isSelected());
        } else {
            Messages.showMessageDialog(MessageResources.message("configuration.folderChooser.error.invalidDirectory.text"),
                    MessageResources.message("configuration.folderChooser.error.invalidDirectory.title"), null);
        }

    }

    JComponent getPanel() {
        return rootComponent;
    }
}

@@ -1646,24 +1646,25 @@
 trim();%0A
+%0A
         
 if (new 
@@ -1655,20 +1655,28 @@
         
-if (
+File file = 
 new File
@@ -1693,161 +1693,62 @@
 ion)
-.canWrite()) %7B%0A            mySettings.setSaveLocation(saveLocation);%0A            mySettings.setSaveOnClose(saveOnCloseField.isSelec
+;%0A        if (!file.isDirectory() %7C%7C !file.canWri
 te
-d
 ())
-;%0A        %7D else
  %7B%0A 
@@ -1987,25 +1987,162 @@
 l);%0A        
-%7D
+    return;%0A        %7D%0A%0A        mySettings.setSaveLocation(saveLocation);%0A        mySettings.setSaveOnClose(saveOnCloseField.isSelected());
 %0A%0A    %7D%0A%0A   

Validate that chosen directory actually is a directory.