/*
 * 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.
 */

/*
 * JdbcHandlers.java
 *
 * Created on November 21, 2003, 10:22 AM
 */

package com.sun.enterprise.tools.admingui.handlers;

import java.util.Iterator;
import java.util.Map;
import java.util.Enumeration;
import java.util.ResourceBundle;

import javax.servlet.http.HttpSession;
import com.iplanet.jato.RequestContext;
import com.iplanet.jato.RequestManager;
import com.iplanet.jato.model.DefaultModel;
import com.iplanet.jato.model.Model;
import com.iplanet.jato.view.View;
import com.iplanet.jato.view.ViewBase;
import com.iplanet.jato.model.ModelControlException;


import com.sun.enterprise.tools.guiframework.exception.FrameworkException;
import com.sun.enterprise.tools.guiframework.model.ModelManager;
import com.sun.enterprise.tools.guiframework.view.DescriptorContainerView;
import com.sun.enterprise.tools.guiframework.view.HandlerContext;
import com.sun.enterprise.tools.guiframework.view.descriptors.ViewDescriptor;

import com.sun.web.ui.model.CCActionTableModelInterface;
import com.sun.web.ui.view.html.CCCheckBox;
import com.sun.web.ui.view.html.CCTextField;

import com.sun.enterprise.connectors.util.ConnectionDefinitionUtils;

public class JdbcConnectionPoolHandlers {
    
    public static final String	PROPERTY_NAME	= "propertyName";
    public static final String	PROPERTY_VALUE 	= "propertyValue";
    
    /** Creates a new instance of JdbcHandlers */
    
    public void getValuesFromStep1(RequestContext ctx, HandlerContext handlerCtx) throws ModelControlException {
	View view = handlerCtx.getView();
	DescriptorContainerView descView = (DescriptorContainerView)(((ViewBase)view));
	ViewDescriptor vd = descView.getViewDescriptor();
	HttpSession session = RequestManager.getSession();
        DefaultModel step1Model = (DefaultModel)(session.getValue("connectionPoolStep1.model"));
        DefaultModel step3Model = (DefaultModel)(session.getValue("connectionPoolStep3.model"));
        String resourceType = (String)step1Model.getValue("ResourceType");
        String vendor = (String)step1Model.getValue("Vendor");
        boolean changed = true;
        if (step3Model != null) {
            if (resourceType != null && 
                resourceType.equals(step3Model.getValue("ResourceType")) &&
                vendor != null &&
                vendor.equals(step3Model.getValue("Vendor"))) {
                    changed = false;
            }
        }
        if (changed) {
            String datasourceClassName = getDatasourceClassName(vendor, resourceType);
            if (datasourceClassName != null) {
                descView.setDisplayFieldValue("DatasourceClassName", datasourceClassName.trim());
            }
            CCActionTableModelInterface model = (CCActionTableModelInterface) handlerCtx.getInputValue("propertiesModel");
            populateProperties(datasourceClassName, model);
        }
        descView.setDisplayFieldValue("Name", step1Model.getValue("Name"));
        descView.setDisplayFieldValue("ResourceType", resourceType);
        descView.setDisplayFieldValue("Vendor", vendor);
    }

    public void setDatasourceClassName(RequestContext ctx, HandlerContext handlerCtx) {
	DescriptorContainerView descView = (DescriptorContainerView)(handlerCtx.getView());
	ViewDescriptor vd = descView.getViewDescriptor();
        String vendor = (String)descView.getDisplayFieldValue("Vendor");
        String resourceType = (String)descView.getDisplayFieldValue("ResourceType");
        String datasourceClassName = getDatasourceClassName(vendor, resourceType);
        if (datasourceClassName != null) {
            descView.setDisplayFieldValue("DatasourceClassName", datasourceClassName.trim());
        }
    }
    
    public void enableGuaranteeIsolation(RequestContext ctx, HandlerContext handlerCtx) {
	View view = handlerCtx.getView();
	CCCheckBox guaranteeIsolation = (CCCheckBox)view;
	DescriptorContainerView descView = (DescriptorContainerView)view.getParent();
	String transIsolation = (String)descView.getDisplayFieldValue("TransactionIsolation");
	
	if (transIsolation != null && transIsolation.length() > 0) {
	    guaranteeIsolation.setDisabled(false);
	}
	else {
	    guaranteeIsolation.setValue("false");
	    guaranteeIsolation.setDisabled(true);
	}
    }
    
    public void enableTableName(RequestContext ctx, HandlerContext handlerCtx) {
	View view = handlerCtx.getView();
	CCTextField tableName = (CCTextField)view;
	DescriptorContainerView descView = (DescriptorContainerView)view.getParent();
	String validMethod = (String)descView.getDisplayFieldValue("ConnectionValidationMethod");
	
	if (validMethod != null && validMethod.equals("table")) {
	    tableName.setDisabled(false);
	}
	else {
	    tableName.setDisabled(true);
	}
    }

    public static String getDatasourceClassName(String vendor, String resourceType) {
        ResourceBundle bundle = 
            ResourceBundle.getBundle("com.sun.enterprise.tools.admingui.resources.JdbcVendors");
        if (vendor != null) {
            try {
                /** properties file should be of the format :
                 *<vendorname>,<resourceType>=<datasourceclassname>
                 **/
                return bundle.getString(vendor.toLowerCase()+","+resourceType);
            } catch (Exception ex) {
                return null; // unknown vendor/resourceType
            }
        }
        return null;
    }
    
    public void populateProperties(String dataSource, 
            CCActionTableModelInterface model) throws ModelControlException{
        String[] defaultProperties = {
            "databaseName", "serverName", "port", "networkProtocol",
            "user", "password", "roleName", "datasourceName" };
        RequestContext ctx = RequestManager.getRequestContext();
        Map properties = null;
        try {
            properties = ConnectionDefinitionUtils.getConnectionDefinitionPropertiesAndDefaults(dataSource.trim());
        } catch (Exception ex) {
            /** deliberately ignore exception when trying to get properties. 
             *this may be because the classname is not in path. default properties
             *would be loaded in this case.
             **/
        }
        if (properties == null || properties.size() == 0) {
            ((DefaultModel)model).clear();
            model.beforeFirst();
            for (int i = 0; i < defaultProperties.length; i++) {
                model.appendRow();
                model.setValue(PROPERTY_NAME, defaultProperties[i]);
                model.setValue(PROPERTY_VALUE, "");
                model.setRowSelected(false);
            }
        }
        else {
            Iterator keys = properties.keySet().iterator();
            ((DefaultModel)model).clear();
            model.beforeFirst();
            while (keys.hasNext()) {
                model.appendRow();
                String name = (String)keys.next();
                model.setValue(PROPERTY_NAME, name);
                model.setValue(PROPERTY_VALUE, properties.get(name));
                model.setRowSelected(false);
            }
        }
    }
    
    public static void main(String __args[]) {
        //test
        System.out.println("DS = " + getDatasourceClassName("sybase" , "javax.sql.XADataSource"));
    }
}
