package gov.va.med.tfs.client.functional;


import static org.junit.Assert.assertEquals;
import gov.va.med.cds.junit.runners.Suite;
import gov.va.med.cds.junit.runners.SuiteAwareSpringRunner;
import gov.va.med.cds.testharness.AbstractBaseTest;

import java.util.HashMap;
import java.util.Map;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.apache.commons.logging.LogFactory;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;


/**
 * Tests the TAFS ManagedBean operations using JMX Connectors
 * 
 * 
 */
@RunWith( SuiteAwareSpringRunner.class )
@ContextConfiguration( locations = { "classpath:gov/va/med/tfs/config/nonWeblogicTfrDataSourceContext.xml" } )


public class ModifyMaintSwitchMBeanTest
    extends
    	AbstractBaseTest
{

    private static final String MBEAN_SERVER_IP = "localhost";
    private static final String MBEAN_SERVER_PORT = "5555";
    private static final String ADMIN_USER_ENV_PROPERTY_NAME = "USER";
    private static final String ADMIN_PASSWORD_ENV_PROPERTY_NAME = "PASSWORD";
    private static final String TAFS_MBEAN_DOMAIN = "gov.va.med.tfs";
    private static final String TAFS_MBEAN_NAME = ":name=Template-Filter-Service";

    private JMXConnector jmxc;
    private ObjectName stdMBeanName;
    private MBeanServerConnection mbsc;

    @Test
    @Suite( groups = "prototypetest" )
    public void verifyMaintSwitchOperationTest( )
        throws Exception
    {
    	setupTemplateManagerMBean( new String[] { "-ip", MBEAN_SERVER_IP, "-port", MBEAN_SERVER_PORT } );

        //Set maint switches to true and verify
        mbsc.invoke( stdMBeanName, "setCreateEnabled", new Object[] { true }, new String[] { "boolean" } );
        mbsc.invoke( stdMBeanName, "setDeleteEnabled", new Object[] { true }, new String[] { "boolean" } );

        System.out.println( "isCreateEnabled: "
                        + mbsc.invoke( stdMBeanName, "isCreateEnabled", null, null ) );
        System.out.println( "isDeleteEnabled: "
                + mbsc.invoke( stdMBeanName, "isDeleteEnabled", null, null ) );
        
        assertEquals( (Boolean) mbsc.invoke( stdMBeanName, "isCreateEnabled", null, null ), true );
        assertEquals( (Boolean) mbsc.invoke( stdMBeanName, "isDeleteEnabled", null, null ), true );

        //Set maint switches to false and verify
        mbsc.invoke( stdMBeanName, "setCreateEnabled", new Object[] { false }, new String[] { "boolean" } );
        mbsc.invoke( stdMBeanName, "setDeleteEnabled", new Object[] { false }, new String[] { "boolean" } );
        
        System.out.println( "isCreateEnabled: "
                + mbsc.invoke( stdMBeanName, "isCreateEnabled", null, null ) );
        System.out.println( "isDeleteEnabled: "
        + mbsc.invoke( stdMBeanName, "isDeleteEnabled", null, null ) );
        
        assertEquals( (Boolean) mbsc.invoke( stdMBeanName, "isCreateEnabled", null, null ), false );
        assertEquals( (Boolean) mbsc.invoke( stdMBeanName, "isDeleteEnabled", null, null ), false );
        
        jmxc.close();

    }

    @BeforeClass
    @Suite( groups = "prototypetest" )
    static public void beforeTemplateCacheResizeMBeanTestClassSetUp( )
        throws Exception
    {
        logger = LogFactory.getLog( ModifyMaintSwitchMBeanTest.class );
    }

    private void setupTemplateManagerMBean( String[] args )
    {
        try
        {
            GetArgs opts = new GetArgs( ModifyMaintSwitchMBeanTest.class, args, "ip:port:user:password:shutdownNow", "ip:port", false );

            String ip = opts.getArg( "ip" );
            String port = opts.getArg( "port" );
            String user = opts.getArg( "user" );
            String password = opts.getArg( "password" );

            // Create an RMI connector client and connect it to the RMI connector server
            JMXServiceURL url = new JMXServiceURL( "service:jmx:rmi:///jndi/rmi://" + ip + ":" + port + "/jmxrmi" );

            // Need to test password against remote server
            Map<String, String> env = new HashMap<String, String>();
            String pkgs = "com.sun.enterprise.admin.jmx.remote.protocol";
            env.put( JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, pkgs );
            env.put( ADMIN_USER_ENV_PROPERTY_NAME, user );
            env.put( ADMIN_PASSWORD_ENV_PROPERTY_NAME, password );

            // Creates a connector client for the connector server at the given address. The resultant client is not
            // connected until its connect method is called.
            jmxc = JMXConnectorFactory.newJMXConnector( url, env );
            jmxc.connect();

            // Get an MBeanServerConnection
            mbsc = jmxc.getMBeanServerConnection();

            // Create FitlerManager MBean
            stdMBeanName = new ObjectName( TAFS_MBEAN_DOMAIN + TAFS_MBEAN_NAME );
            mbsc.getObjectInstance( stdMBeanName );
        }
        catch ( Exception e )
        {
            if ( e.getMessage().startsWith( "Failed to retrieve RMIServer stub" ) )
            {
                if ( logger.isErrorEnabled() )
                {
                    logger.error( "\nFailed to retrieve RMIServer stub.  Template Manager not running at the specified location." );
                }
            }
            else
            {
                e.printStackTrace();
            }
        }
    }
}
