/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.netbeans.modules.fish.payara.jakarta.transformer;

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import org.openide.WizardDescriptor;
import org.openide.WizardValidationException;
import org.openide.filesystems.FileUtil;

public class TransformerPanelVisual extends JPanel {
  
    private final TransformerWizardPanel panel;
           
    private boolean override;

    public TransformerPanelVisual(TransformerWizardPanel panel) {
        initComponents();
        this.panel = panel;
        
        DocumentListener updateListener = new DocumentListener() {
            @Override public void insertUpdate(DocumentEvent e) { panel.fireChangeEvent(); }
            @Override public void removeUpdate(DocumentEvent e) { panel.fireChangeEvent(); }
            @Override public void changedUpdate(DocumentEvent e) { panel.fireChangeEvent(); }
        };
        this.source.getDocument().addDocumentListener(updateListener);
        this.target.getDocument().addDocumentListener(updateListener);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        selectSourceButton = new javax.swing.JButton();
        source = new javax.swing.JTextField();
        target = new javax.swing.JTextField();
        selectTargetButton = new javax.swing.JButton();
        overrideCheckBox = new javax.swing.JCheckBox();

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(TransformerPanelVisual.class, "transformerPanelVisual.jLabel1.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(TransformerPanelVisual.class, "transformerPanelVisual.jLabel2.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(selectSourceButton, org.openide.util.NbBundle.getMessage(TransformerPanelVisual.class, "transformerPanelVisual.selectSourceFolder.text")); // NOI18N
        selectSourceButton.setActionCommand(org.openide.util.NbBundle.getMessage(TransformerPanelVisual.class, "transformerPanelVisual.selectSourceFolder.actionCommand")); // NOI18N
        selectSourceButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectSourceButtonActionPerformed(evt);
            }
        });

        source.setName("source"); // NOI18N

        target.setName("target"); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(selectTargetButton, org.openide.util.NbBundle.getMessage(TransformerPanelVisual.class, "transformerPanelVisual.selectTargetFolder.text")); // NOI18N
        selectTargetButton.setActionCommand(org.openide.util.NbBundle.getMessage(TransformerPanelVisual.class, "transformerPanelVisual.selectTargetFolder.actionCommand")); // NOI18N
        selectTargetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectTargetButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(overrideCheckBox, org.openide.util.NbBundle.getMessage(TransformerPanelVisual.class, "transformerPanelVisual.overrideCheckBox.text")); // NOI18N
        overrideCheckBox.setToolTipText(org.openide.util.NbBundle.getMessage(TransformerPanelVisual.class, "transformerPanelVisual.overrideCheckBox.tooltip")); // NOI18N
        overrideCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                overrideCheckBoxActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(source, javax.swing.GroupLayout.DEFAULT_SIZE, 310, Short.MAX_VALUE)
                            .addComponent(target))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(selectSourceButton, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(selectTargetButton, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(overrideCheckBox)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(selectSourceButton)
                    .addComponent(source, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(target, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(selectTargetButton))
                .addGap(18, 18, 18)
                .addComponent(overrideCheckBox)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void selectSourceButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectSourceButtonActionPerformed
        String command = evt.getActionCommand();
        if ("BROWSE".equals(command)) {
            JFileChooser chooser = new JFileChooser();
            //FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
            chooser.setCurrentDirectory(chooser.getCurrentDirectory());            
            chooser.setDialogTitle("Select source to transform");
            chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            String path = this.source.getText();
            if (path.length() > 0) {
                File f = new File(path);
                if (f.exists()) {
                    chooser.setSelectedFile(f);
                }
            }
            if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) {
                File projectDir = chooser.getSelectedFile();
                source.setText(FileUtil.normalizeFile(projectDir).getAbsolutePath());
            }
            panel.fireChangeEvent();
        }
    }//GEN-LAST:event_selectSourceButtonActionPerformed

    private void selectTargetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectTargetButtonActionPerformed
        String command = evt.getActionCommand();
        if ("BROWSE".equals(command)) {
            JFileChooser chooser = new JFileChooser();
            //FileUtil.preventFileChooserSymlinkTraversal(chooser, null);
            chooser.setCurrentDirectory(chooser.getCurrentDirectory());            
            chooser.setDialogTitle("Select Folder to Transform");
            chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            String path = this.target.getText();
            if (path.length() > 0) {
                File f = new File(path);
                if (f.exists()) {
                    chooser.setSelectedFile(f);
                }
            }
            if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) {
                File projectDir = chooser.getSelectedFile();
                target.setText(FileUtil.normalizeFile(projectDir).getAbsolutePath());
            }
            panel.fireChangeEvent();
        }
    }//GEN-LAST:event_selectTargetButtonActionPerformed

    private void overrideCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_overrideCheckBoxActionPerformed
        if(evt.getActionCommand().equals("Override")){
            if(overrideCheckBox.isSelected()){
                target.setText("");
                target.setEnabled(false);
                selectTargetButton.setEnabled(false);
                override = true;               
            } else {                
                target.setEnabled(true);
                selectTargetButton.setEnabled(true); 
                override = false;                
            }
            panel.fireChangeEvent();
        }
    }//GEN-LAST:event_overrideCheckBoxActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JCheckBox overrideCheckBox;
    private javax.swing.JButton selectSourceButton;
    private javax.swing.JButton selectTargetButton;
    private javax.swing.JTextField source;
    private javax.swing.JTextField target;
    // End of variables declaration//GEN-END:variables

    @Override
    public void addNotify() {
        super.addNotify();
    }

    boolean valid(WizardDescriptor wizardDescriptor) throws WizardValidationException {
        return validate(wizardDescriptor);
    }

    void store(WizardDescriptor d) {      
        d.putProperty("sourceSelected", this.source.getText().trim());
        d.putProperty("targetSelected", this.target.getText().trim());  
        d.putProperty("override", override);
    }

    void read(WizardDescriptor settings) {
       
    }

    boolean validate(WizardDescriptor d) throws WizardValidationException {
        String source = this.source.getText().trim();
        String target = this.target.getText().trim();
        File sourceFile = new File(source);
        File targetFile = new File(target);
        
        //checking if the source was selected
        if(source.isEmpty()) {
            d.putProperty("WizardPanel_errorMessage",
                    "You must select a source folder or file.");            
            return false;
        }

        if(!sourceFile.exists()) {
            d.putProperty("WizardPanel_errorMessage",
                    "You must select a valid source folder or file.");
            return false;
        }
        
        if(override && target.isEmpty()) {
            d.putProperty("WizardPanel_errorMessage",
                    null);  
            return true;
        }
        
        if(!override && target.isEmpty()) {
            d.putProperty("WizardPanel_errorMessage",
                    "You must select a target folder or file.");             
            return false;
        }
        
                 
        //validation of second param when folder is selected as the source
        if(!override && sourceFile.isDirectory()) {
            if(!targetFile.exists()) {
                d.putProperty("WizardPanel_errorMessage",
                        "You must select a valid target folder.");
                return false;
            }
            if(!targetFile.isDirectory()) {
                d.putProperty("WizardPanel_errorMessage",
                    "You must select a target folder.");
                return false;
            }
        }       
        
        if(!override && sourceFile.isFile()) {
            if(!targetFile.exists()) {
                d.putProperty("WizardPanel_errorMessage",
                        "You must select a valid target file.");
                return false;
            }
            
            if(!targetFile.isDirectory()) {
                d.putProperty("WizardPanel_errorMessage",
                        "You must select a target directory.");
                return false;
            }
        }
        
        if(!source.isEmpty() && !target.isEmpty()) {
            d.putProperty("WizardPanel_errorMessage",
                    null);
        }
        
         return true;       
    } 
  
}
