/*
 * Copyright 2007 - 2023 Ralf Wisser.
 *
 * Licensed 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 net.sf.jailer.ui;

import java.awt.Frame;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JLabel;

import org.fife.rsta.ui.EscapableDialog;

import net.sf.jailer.ExecutionContext;
import net.sf.jailer.ui.DbConnectionDialog.ConnectionInfo;

/**
 * Assembles cli arguments that starts the application.
 * 
 * @author Ralf Wisser
 */
public class CLIPanel extends javax.swing.JPanel {

	private final DbConnectionDialog connectionDialog;
	private final ExecutionContext executionContext;
	private final boolean forDataBrowser;
	private final String extractionModelFile;
	private final String rawSchemaMapping;
	private final List<String> bookmarks;
	private final String bookmark;
	private EscapableDialog dialog;
	
	/**
	 * Creates new form CLIPanel
	 */
	public CLIPanel(DbConnectionDialog connectionDialog, boolean forDataBrowser, String extractionModelFile,
			String rawSchemaMapping, List<String> bookmarks, String bookmark, ExecutionContext executionContext) {
		this.connectionDialog = connectionDialog;
		this.forDataBrowser = forDataBrowser;
		this.extractionModelFile = extractionModelFile;
		this.rawSchemaMapping = rawSchemaMapping;
		this.bookmarks = bookmarks;
		this.bookmark = bookmark;
		this.executionContext = executionContext;
		initComponents(); UIUtil.initComponents(this);
		copyButton.setIcon(UIUtil.scaleIcon(new JLabel(""), UIUtil.readImage("/copy.png")));
		closeButton.setIcon(UIUtil.scaleIcon(new JLabel(""), UIUtil.readImage("/buttoncancel.png")));
	}

    public void open(Frame owner) {
    	if (bookmarks != null) {
    		DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
    		model.addElement("");
    		for (String bm:bookmarks) {
        		model.addElement(bm);
    		}
			bookmarkComboBox.setModel(model);
			bookmarkComboBox.setSelectedItem(bookmark != null? bookmark : "");
    		bookmarkPanel.setVisible(true);
    	} else {
    		bookmarkPanel.setVisible(false);
    	}
    	updateCLIArea();
    	dialog = new EscapableDialog(owner, "Command Line") {
        };
        dialog.setModal(true);
 		dialog.getContentPane().add(this);
 		dialog.pack();
 		dialog.setSize(700, 240);
 		dialog.setLocation(owner.getX() + (owner.getWidth() - dialog.getWidth()) / 2, Math.max(0, owner.getY() + (owner.getHeight() - dialog.getHeight()) / 2));
 		UIUtil.fit(dialog);
 		dialog.setVisible(true);
    }

	/**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        jinfoLabe = new javax.swing.JLabel();
        commandLinePanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        cliArea = new javax.swing.JTextArea();
        copyButton = new javax.swing.JButton();
        closeButton = new javax.swing.JButton();
        bookmarkPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        bookmarkComboBox = new javax.swing.JComboBox<>();

        setLayout(new java.awt.GridBagLayout());

        jPanel1.setLayout(new java.awt.GridBagLayout());

        jinfoLabe.setFont(jinfoLabe.getFont().deriveFont(jinfoLabe.getFont().getSize()+2f));
        jinfoLabe.setText("<html>These command-line arguments cause the application to start in a state that is identical to the current one.<hr></html>");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(0, 4, 4, 0);
        jPanel1.add(jinfoLabe, gridBagConstraints);

        commandLinePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Command line"));
        commandLinePanel.setLayout(new java.awt.GridBagLayout());

        jScrollPane1.setBorder(new javax.swing.border.LineBorder(java.awt.Color.gray, 1, true));
        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

        cliArea.setEditable(false);
        cliArea.setColumns(20);
        cliArea.setLineWrap(true);
        cliArea.setWrapStyleWord(true);
        cliArea.setMaximumSize(new java.awt.Dimension(300, 2147483647));
        jScrollPane1.setViewportView(cliArea);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        commandLinePanel.add(jScrollPane1, gridBagConstraints);

        copyButton.setText("Copy to Clipboard"); // NOI18N
        copyButton.setToolTipText("Copy to Clipboard"); // NOI18N
        copyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                copyButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(4, 0, 0, 0);
        commandLinePanel.add(copyButton, gridBagConstraints);

        closeButton.setText(" Close ");
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(4, 0, 0, 0);
        commandLinePanel.add(closeButton, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 6;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        jPanel1.add(commandLinePanel, gridBagConstraints);

        bookmarkPanel.setLayout(new java.awt.GridBagLayout());

        jLabel1.setText("Open Bookmark  ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        bookmarkPanel.add(jLabel1, gridBagConstraints);

        bookmarkComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        bookmarkComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bookmarkComboBoxActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        bookmarkPanel.add(bookmarkComboBox, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 4, 8, 0);
        jPanel1.add(bookmarkPanel, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 2, 0, 2);
        add(jPanel1, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents

    private void copyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copyButtonActionPerformed
        cliArea.selectAll();
        cliArea.copy();
        updateCLIArea();
    }//GEN-LAST:event_copyButtonActionPerformed
    
	private void updateCLIArea() {
		List<String> args = new ArrayList<String>();
		String cmd = "jailerGUI";
		String cmdWithExt = "sh " + cmd + ".sh";
		if (System.getProperty("os.name", "").toLowerCase(Locale.ENGLISH).startsWith("windows")) {
			cmdWithExt = cmd + ".bat";
		}

		if (extractionModelFile != null) {
			args.add(extractionModelFile);
		}

		String user = null;
		String password = null;
		if (connectionDialog != null && connectionDialog.isConnected) {
			ConnectionInfo currentConnection = connectionDialog.currentConnection;
			user = currentConnection.user;
			password = "<password>";
			
			args.add("-url");
			args.add(currentConnection.url);
			args.add("-user");
			args.add(user);
			args.add("-password");
			args.add(password);
			
			if (!isEmpty(currentConnection.jar1)) {
				args.add("-jdbcjar");
				args.add(currentConnection.jar1);
			}
			if (!isEmpty(currentConnection.jar2)) {
				args.add("-jdbcjar2");
				args.add(currentConnection.jar2);
			}
			if (!isEmpty(currentConnection.jar3)) {
				args.add("-jdbcjar3");
				args.add(currentConnection.jar3);
			}
			if (!isEmpty(currentConnection.jar4)) {
				args.add("-jdbcjar4");
				args.add(currentConnection.jar4);
			}
			
			if (!isEmpty(currentConnection.driverClass)) {
				args.add("-driver");
				args.add(currentConnection.driverClass);
			}
		}
		
//		if (extractionModelFile == null) {
			args.add("-datamodel");
			args.add(executionContext.getQualifiedDatamodelFolder());
//		}
		
		if (bookmarks != null) {
			Object bm = bookmarkComboBox.getSelectedItem();
			if (bm != null && !bm.toString().isEmpty()) {
				args.add("-bookmark");
				args.add(bm.toString());
			}
		}

		if (rawSchemaMapping != null && !rawSchemaMapping.trim().isEmpty()) {
			args.add("-schemamapping");
			args.add(rawSchemaMapping);
		}
		String cli = cmdWithExt + UIUtil.createPlainCLIArguments(user, password, args, false);
		cliArea.setText(cli);
		cliArea.setCaretPosition(0);
		jScrollPane1.getViewport().setViewPosition(new Point(0,0));
	}

    private boolean isEmpty(String x) {
		return x == null || x.isEmpty();
	}

	private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
        dialog.setVisible(false);
        dialog.dispose();
    }//GEN-LAST:event_closeButtonActionPerformed

    private void bookmarkComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bookmarkComboBoxActionPerformed
    	updateCLIArea();
    }//GEN-LAST:event_bookmarkComboBoxActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox<String> bookmarkComboBox;
    private javax.swing.JPanel bookmarkPanel;
    private javax.swing.JTextArea cliArea;
    private javax.swing.JButton closeButton;
    private javax.swing.JPanel commandLinePanel;
    private javax.swing.JButton copyButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel jinfoLabe;
    // End of variables declaration//GEN-END:variables
}
