/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

/*
 * CertificatePanel.java
 *
 * Created on September 29, 2003, 2:07 PM
 */

package com.sun.enterprise.tools.upgrade.gui;

/**
 *
 * @author  prakash
 */
import java.util.*;
import com.sun.enterprise.tools.upgrade.common.*;
import com.sun.enterprise.tools.upgrade.gui.util.*;
import java.util.logging.*;
import java.io.File;

import com.sun.enterprise.util.i18n.StringManager;
import com.sun.enterprise.tools.upgrade.logging.*;

public class CertificatePanel extends javax.swing.JPanel {

    // Variables declaration - do not modify//
    private javax.swing.JButton addDomainButton;
    private javax.swing.JButton deleteDomainButton;
    private javax.swing.JTable domainTable;
    private DomainsTableModel domainsTableModel;
    private javax.swing.JScrollPane domainTableScrollPane;

    private CommonInfoModel commonInfoModel;
    private javax.swing.JFrame parent = null;
    private List domainNamesInTable = null;
    private AddDomainDialog addDomainDialog = null;

    private StringManager stringManager = StringManager.getManager("com.sun.enterprise.tools.upgrade.gui");
    private Logger logger = com.sun.enterprise.tools.upgrade.common.CommonInfoModel.getDefaultLogger();


    /** Creates new form CertificatePanel */
    public CertificatePanel(CommonInfoModel model, javax.swing.JFrame parent) {
        this.commonInfoModel = model;
        this.parent = parent;
        this.domainNamesInTable = new ArrayList();
        initComponents();
    }

    /** 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.
     */
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        javax.swing.JPanel tablePanel = new javax.swing.JPanel();
        domainTableScrollPane = new javax.swing.JScrollPane();
        domainTable = new javax.swing.JTable();
        addDomainButton = new javax.swing.JButton();
        addDomainButton.addActionListener(new java.awt.event.ActionListener(){
            public void actionPerformed(java.awt.event.ActionEvent ae){
                performAddDomainAction();
            }
        });
        deleteDomainButton = new javax.swing.JButton();
        deleteDomainButton.addActionListener(new java.awt.event.ActionListener(){
            public void actionPerformed(java.awt.event.ActionEvent ae){
                performDeleteDomainAction();
            }
        });
        javax.swing.JPanel dummyPanel1 = new javax.swing.JPanel();
        javax.swing.JPanel dummyPanel2 = new javax.swing.JPanel();

        javax.swing.JPanel dummyContentPanel = new javax.swing.JPanel();

        this.setLayout(new java.awt.BorderLayout());
        HeaderPanel headerPanel = new HeaderPanel(stringManager.getString("upgrade.gui.certpanel.headerPanel"));
        headerPanel.setInsets(new java.awt.Insets(12, 10, 5, 10));
        this.add(headerPanel, "North");

        dummyContentPanel.setLayout(new java.awt.GridBagLayout());
        FlowLabel flowContentLabel = new FlowLabel();
        flowContentLabel.setText(stringManager.getString("upgrade.gui.certpanel.flowContentLabel"));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(0, 10, 10, 10);
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 0.0;
        dummyContentPanel.add(flowContentLabel, gridBagConstraints);

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

        tablePanel.setBorder(new javax.swing.border.TitledBorder(stringManager.getString("upgrade.gui.certpanel.certPanelTitle")));
        domainsTableModel = new DomainsTableModel(domainNamesInTable);
        domainTable.setModel(domainsTableModel);

        domainTableScrollPane.setViewportView(domainTable);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        tablePanel.add(domainTableScrollPane, gridBagConstraints);

        addDomainButton.setText(stringManager.getString("upgrade.gui.certpanel.addDomainButtonText"));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new java.awt.Insets(10, 15, 10, 10);
        tablePanel.add(addDomainButton, gridBagConstraints);

        deleteDomainButton.setText(stringManager.getString("upgrade.gui.certpanel.deleteDomainButtonText"));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(10, 15, 10, 10);
        tablePanel.add(deleteDomainButton, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
        gridBagConstraints.weighty = 0.5;
        tablePanel.add(dummyPanel1, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
        gridBagConstraints.weighty = 0.5;
        tablePanel.add(dummyPanel2, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridheight = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        dummyContentPanel.add(tablePanel, gridBagConstraints);

        add(dummyContentPanel, java.awt.BorderLayout.CENTER);

    }
    void performAddDomainAction(){
        getAddDomainDialog().clearFields();
        getAddDomainDialog().setVisible(true);
    }
    void performDeleteDomainAction(){
        int selRow = this.domainTable.getSelectedRow();
        if(selRow != -1){
            int option = javax.swing.JOptionPane.showConfirmDialog(this, stringManager.getString("upgrade.gui.certpanel.deleteConfirmMsg"),
						      stringManager.getString("upgrade.gui.certpanel.deleteConfirmTitle"),
						      javax.swing.JOptionPane.YES_NO_OPTION,
						      javax.swing.JOptionPane.QUESTION_MESSAGE);
            if (option == javax.swing.JOptionPane.NO_OPTION) {
                return;
            }
            commonInfoModel.setCertDbPassword((String)domainNamesInTable.get(selRow),"");
            commonInfoModel.setJksKeystorePassword((String)domainNamesInTable.get(selRow),"");
            domainsTableModel.removeDomain(selRow);
        }
    }
    private AddDomainDialog getAddDomainDialog(){
        if(this.addDomainDialog == null){
            int sourceToTarget = 0;
            if(this.commonInfoModel.isUpgradeNSStoJKS()){
                sourceToTarget = AddDomainDialog.NSStoJKS;
            }else if(this.commonInfoModel.isUpgradeJKStoJKS()){
                sourceToTarget = AddDomainDialog.JKStoJKS;
            }else if(this.commonInfoModel.isUpgradeJKStoNSS()){
                sourceToTarget = AddDomainDialog.JKStoNSS;
            }else{
                sourceToTarget = AddDomainDialog.NSStoNSS; //NSS to NSS
            }    
            
            addDomainDialog = new AddDomainDialog(parent, true, commonInfoModel, sourceToTarget);
            centerDialog(addDomainDialog);
            addDomainDialog.addDialogListener(new DialogListener(){
                public void dialogProcessed(DialogEvent evt){
                    processAddDomainDialogEvent(evt);
                }
            });
        }
        return addDomainDialog;
    }
    public void reInitializeAddDomainDialog(){
        this.addDomainDialog = null;
    }
    public void centerDialog(javax.swing.JDialog dialog) {
        java.awt.Rectangle bounds = parent.getBounds();

        java.awt.Rectangle dialogLocation = new java.awt.Rectangle();
        dialogLocation.x = bounds.x+((bounds.width-dialog.getWidth())/2);
        dialogLocation.y = bounds.y+((bounds.height-dialog.getHeight())/2);
        dialogLocation.setSize(dialog.getWidth(),dialog.getHeight());
        dialog.setBounds(dialogLocation);

    }
    private java.util.List processv70PESEto8xPE(String selectedDomainName, String selectedInstanceName, String pwd1, String pwd2, String pwd3){
        // Here call a post validation of passwords and their setting in commonInfoModel has to be made.
        // Whatever validation is done in CLI should be done here.  Instead of doing validation in two places, the validation code
        // can be moved to UpgradeUtils (avoid doing it in CommonInfoModel (just a data holder)).
        // You can call this UpgradeUtils.... method from both CLI and here.

        // If there are no errors, retun null from this method.  If there are errors, get the localized error message and erro title
        // and return them as a list. list.get(0) should be the message, hand list.get(1) should be title of error message.
        commonInfoModel.setCurrentDomain(selectedDomainName);
        commonInfoModel.setCurrentSourceInstance(selectedInstanceName);
        commonInfoModel.setCertDbPassword(pwd1);
        boolean validpwd = PasswordVerifier.verifySourceNSSPassword(commonInfoModel);
        if(!validpwd) {
            commonInfoModel.recover();
            List errorList = new ArrayList();
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidNSSPWDMsg"));
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidNSSPWDTitle"));
            return errorList;
        }

        commonInfoModel.setJksKeystorePassword(pwd2);
        String jksPath=commonInfoModel.getTargetJKSKeyStorePath();
        validpwd = PasswordVerifier.verifyKeystorePassword(jksPath,pwd2 );
        if(!validpwd) {
            commonInfoModel.recover();
            List errorList = new ArrayList();
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidJKSPWDMsg"));
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidJKSPWDTitle"));
            return errorList;
        }

        commonInfoModel.setJksCAKeystorePassword(pwd3);
        String trustJksPath=commonInfoModel.getTargetTrustedJKSKeyStorePath();
        validpwd = PasswordVerifier.verifyKeystorePassword(trustJksPath,pwd3 );
        if(!validpwd) {
            commonInfoModel.recover();
            List errorList = new ArrayList();
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidCAPWDMsg"));
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidCAPWDTitle"));
            return errorList;
        }
        return null;
    }
    private java.util.List processv8xPEto8xSEEE(String selectedDomainName, String pwd1, String pwd2, String pwd3){
        // Follow the above for rest of the methods.
        commonInfoModel.setCurrentDomain(selectedDomainName);
        commonInfoModel.setCertDbPassword(pwd3);
        commonInfoModel.setTargetCertDbPassword(pwd3);
        boolean validpwd = PasswordVerifier.verifyTargetNSSPassword(commonInfoModel,commonInfoModel.getTargetConfig());
        if(!validpwd) {
            commonInfoModel.recover();
            List errorList = new ArrayList();
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidTargetNSSPWDMsg"));
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidTargetNSSPWDTitle"));
            return errorList;
        }
        commonInfoModel.setJksKeystorePassword(pwd1);
        String jksPath=commonInfoModel.getSourceJKSKeyStorePath();
        validpwd = PasswordVerifier.verifyKeystorePassword(jksPath,pwd1 );
        if(!validpwd) {
            commonInfoModel.recover();
            List errorList = new ArrayList();
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidJKSPWDMsg"));
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidJKSPWDTitle"));
            return errorList;
        }
        commonInfoModel.setJksCAKeystorePassword(pwd2);
        String trustJksPath=commonInfoModel.getSourceTrustedJKSKeyStorePath();
        validpwd = PasswordVerifier.verifyKeystorePassword(trustJksPath,pwd2 );
        if(!validpwd) {
            commonInfoModel.recover();
            List errorList = new ArrayList();
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidCAPWDMsg"));
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidCAPWDTitle"));
            return errorList;
        }
        return null;
    }
    private java.util.List processv80PEto81PE(String selectedDomainName, String pwd1, String pwd2){
        commonInfoModel.setCurrentDomain(selectedDomainName);
        commonInfoModel.setJksKeystorePassword(pwd1);
        String jksPath=commonInfoModel.getSourceJKSKeyStorePath();
        boolean validpwd = PasswordVerifier.verifyKeystorePassword(jksPath,pwd1 );
        if(!validpwd) {
            commonInfoModel.recover();
            List errorList = new ArrayList();
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidJKSPWDMsg"));
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidJKSPWDTitle"));
            return errorList;
        }

        commonInfoModel.setJksCAKeystorePassword(pwd2);
        String trustJksPath=commonInfoModel.getSourceTrustedJKSKeyStorePath();
        validpwd = PasswordVerifier.verifyKeystorePassword(trustJksPath,pwd2 );
        if(!validpwd) {
            commonInfoModel.recover();
            List errorList = new ArrayList();
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidCAPWDMsg"));
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidCAPWDTitle"));
            return errorList;
        }
        return null;
    }
    private java.util.List processv7xEEto90EE(String selectedDomainName, String selectedInstanceName, String pwd1, String pwd2){
        commonInfoModel.setCurrentDomain(selectedDomainName);
        commonInfoModel.setCurrentSourceInstance(selectedInstanceName);
        commonInfoModel.setCertDbPassword(pwd1);
        boolean validpwd = PasswordVerifier.verifySourceNSSPassword(commonInfoModel);
        if(!validpwd) {
            commonInfoModel.recover();
            List errorList = new ArrayList();
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidNSSPWDMsg"));
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidNSSPWDTitle"));
            return errorList;
        }
        commonInfoModel.setTargetCertDbPassword(pwd2);
        validpwd = PasswordVerifier.verifyTargetNSSPassword(commonInfoModel,commonInfoModel.getTargetConfig());
        if(!validpwd) {
            commonInfoModel.recover();
            List errorList = new ArrayList();
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidTargetNSSPWDMsg"));
            errorList.add(stringManager.getString("upgrade.gui.certpanel.invalidTargetNSSPWDTitle"));
            return errorList;
        }
        return null;
    }

    private void processAddDomainDialogEvent(DialogEvent evt){
        if(evt.getAction() == DialogEvent.CANCEL_ACTION){
            addDomainDialog.setVisible(false);
            addDomainDialog.dispose();
        }if(evt.getAction() == DialogEvent.HELP_ACTION){
            // process help action
        }else if(evt.getAction() == DialogEvent.FINISH_ACTION){
            java.util.Vector data = (java.util.Vector)evt.getObject();
            int sourceToTargetVersion = ((Integer)data.get(0)).intValue();
            if(data.get(1) == null || data.size() < 4){
                // log a error message and return.
                javax.swing.JOptionPane.showMessageDialog(this,stringManager.getString("upgrade.gui.certpanel.chooseDomainMsg"),stringManager.getString("upgrade.gui.certpanel.chooseDomainTitle"),javax.swing.JOptionPane.ERROR_MESSAGE);
                return;
            }
            String domainTableEntry = (String)data.get(1);
            if(commonInfoModel.getSourceVersion().equals(UpgradeConstants.VERSION_7X)) {
                domainTableEntry = domainTableEntry + ":" + (String)data.get(2);
            }
            if(!this.domainNamesInTable.contains(domainTableEntry)) {
                domainsTableModel.addDomain(domainTableEntry);
                commonInfoModel.addDomainOptionName(domainTableEntry);
            }
            if(sourceToTargetVersion == AddDomainDialog.NSStoJKS && (data.size() > 5)){
                java.util.List errorMessageList = this.processv70PESEto8xPE((String)data.get(1), (String)data.get(2), (String)data.get(3),(String)data.get(4),(String)data.get(5));
                if(errorMessageList != null){
                    // messageList contains message and title of the error
                    javax.swing.JOptionPane.showMessageDialog(this, (String)errorMessageList.get(0),(String)errorMessageList.get(1),javax.swing.JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }else if(sourceToTargetVersion == AddDomainDialog.JKStoNSS && (data.size() > 5)){
                java.util.List errorMessageList = this.processv8xPEto8xSEEE((String)data.get(1),(String)data.get(3),(String)data.get(4),(String)data.get(5));
                if(errorMessageList != null){
                    // messageList contains message and title of the error
                    javax.swing.JOptionPane.showMessageDialog(this, (String)errorMessageList.get(0),(String)errorMessageList.get(1),javax.swing.JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }else if(sourceToTargetVersion == AddDomainDialog.JKStoJKS && (data.size() > 4)){
                java.util.List errorMessageList = this.processv80PEto81PE((String)data.get(1),(String)data.get(3),(String)data.get(4));
                if(errorMessageList != null){
                    // messageList contains message and title of the error
                    javax.swing.JOptionPane.showMessageDialog(this, (String)errorMessageList.get(0),(String)errorMessageList.get(1),javax.swing.JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }else if(sourceToTargetVersion == AddDomainDialog.NSStoNSS && (data.size() > 4)){
                //AddDomainDialog.v70SEto81SE
                java.util.List errorMessageList = this.processv7xEEto90EE((String)data.get(1),(String)data.get(2),(String)data.get(3), (String)data.get(4));
                if(errorMessageList != null){
                    // messageList contains message and title of the error
                    javax.swing.JOptionPane.showMessageDialog(this, (String)errorMessageList.get(0),(String)errorMessageList.get(1),javax.swing.JOptionPane.ERROR_MESSAGE);
                    return;
                }
            } else {
                javax.swing.JOptionPane.showMessageDialog(this,stringManager.getString("upgrade.gui.certpanel.chooseDomainMsg"),stringManager.getString("upgrade.gui.certpanel.chooseDomainTitle"),javax.swing.JOptionPane.ERROR_MESSAGE);
                return;
            }
            addDomainDialog.setVisible(false);
            addDomainDialog.dispose();
        }
    }
    // Table model for exceptions table
    class DomainsTableModel extends javax.swing.table.AbstractTableModel {
	private List domains = null;
	private String columnNames[] = {stringManager.getString("upgrade.gui.certpanel.tableColumnName")};
	/**
	 * FileTableModel constructor comment.
	 */
	public DomainsTableModel(List doms) {
	    super();
            this.domains = doms;
	}
	public int getColumnCount() {
	    return columnNames.length;
	}
	public java.lang.String getColumnName(int column) {
	    return columnNames[column];
	}

	public int getRowCount() {
	    return domains.size();
	}
	public boolean isCellEditable(int row, int col) {
	    return false;
	}
	public Class getColumnClass(int c) {
	    return java.lang.String.class;
	}
	/**
	 * getValueAt method comment.
	 */
	public Object getValueAt(int row, int col) {
	    return (String) domains.get(row);
	}
        public void removeDomain(int domainIndex){
            if(domains.size() > domainIndex){
                domains.remove(domainIndex);
                fireTableDataChanged();
            }
        }
        public void addDomain(String domainName){
            if(domainName != null){
                domains.add(domainName);
                fireTableDataChanged();
            }
        }
    }
}
