/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2010, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.as.test.manualmode.jca.moduledeployment;

import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ContainerResource;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.test.integration.management.ManagementOperations;
import org.jboss.as.test.integration.management.base.AbstractMgmtTestBase;
import org.jboss.as.test.integration.management.util.MgmtOperationException;
import org.jboss.as.test.shared.FileUtils;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.dmr.ModelNode;
import org.jboss.logging.Logger;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.StringAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.staxmapper.XMLElementReader;
import org.jboss.staxmapper.XMLElementWriter;
import org.junit.Test;

import javax.naming.InitialContext;
import javax.resource.cci.ConnectionFactory;
import java.util.Iterator;
import java.util.Set;

import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

/**
 * AS7-5768 -Support for RA module deployment
 *
 * @author <a href="vrastsel@redhat.com">Vladimir Rastseluev</a>
 * @author <a href="istudens@redhat.com">Ivo Studensky</a>
 */
public abstract class AbstractModuleDeploymentTestCase extends
        AbstractMgmtTestBase {

    protected static Logger LOGGER = Logger.getLogger(AbstractModuleDeploymentTestCase.class);

    protected static final String CONTAINER = "default-jbossas";
    protected static final String DEFAULT_DEPLOYMENT = "multiple.jar";


    protected static final ModelNode SUBSYSTEM_PATH = new ModelNode().add("subsystem", "resource-adapters");

    @ContainerResource(CONTAINER)
    protected ManagementClient managementClient;

    @ArquillianResource
    protected ContainerController container;

    @ArquillianResource
    protected Deployer deployer;

    @Override
    protected ModelControllerClient getModelControllerClient() {
        return getManagementClient().getControllerClient();
    }

    protected ManagementClient getManagementClient() {
        final ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient();
        ManagementClient managementClient = new ManagementClient(client, TestSuiteEnvironment.getServerAddress(),
                TestSuiteEnvironment.getServerPort());
        return managementClient;
    }

    @Test
    @InSequence(-1)
    @RunAsClient
    public void prepareServer() throws Exception {
        container.start(CONTAINER);
        doPrepareServer(getManagementClient());
        if (getDeploymentName() != null) {
            deployer.deploy(getDeploymentName());
        }
    }

    @Test
    @InSequence(1)
    @RunAsClient
    public void tearDownServer() throws Exception {
        try {
            if (getDeploymentName() != null) {
                deployer.undeploy(getDeploymentName());
            }
        } finally {
            try {
                doTearDownServer(getManagementClient());
            } finally {
                container.stop(CONTAINER);
            }
        }
    }

    protected abstract void doPrepareServer(ManagementClient managementClient) throws Exception;

    protected abstract void doTearDownServer(ManagementClient managementClient) throws Exception;

    protected String getDeploymentName() {
        return DEFAULT_DEPLOYMENT;
    }

    /**
     * Define the deployment
     *
     * @return The deployment archive
     */
    public static JavaArchive createDeployment(boolean withDependencies) throws Exception {
        JavaArchive ja = ShrinkWrap.create(JavaArchive.class, DEFAULT_DEPLOYMENT);
        ja.addClasses(MgmtOperationException.class, XMLElementReader.class,
                XMLElementWriter.class);
        ja.addClasses(TestSuiteEnvironment.class, ManagementOperations.class, FileUtils.class);

        ja.addPackage(AbstractMgmtTestBase.class.getPackage())
                .addPackage(AbstractModuleDeploymentTestCase.class.getPackage());

        if (withDependencies)
            ja.addAsManifestResource(
                    new StringAsset(
                            "Dependencies: org.jboss.as.controller-client,org.jboss.dmr,org.jboss.as.cli,javax.inject.api,org.jboss.as.connector\n"),
                    "MANIFEST.MF");

        return ja;

    }

    /**
     * Define the deployment
     *
     * @return The deployment archive
     */
    public static JavaArchive createDeployment() throws Exception {
        return createDeployment(true);
    }

    /**
     * Test configuration
     *
     * @throws Throwable in case of an error
     */
    public void testConnectionFactory(ConnectionFactory connectionFactory)
            throws Throwable {
        assertNotNull(connectionFactory);
        assertNotNull(connectionFactory.getConnection());
    }

    /**
     * Tests connection in pool
     *
     * @throws Exception in case of error
     */
    public void testConnection(final ModelNode address, final String conName) throws Exception {
        final ModelNode address1 = address.clone();
        address1.add("connection-definitions", conName);
        address1.protect();

        final ModelNode operation1 = new ModelNode();
        operation1.get(OP).set("test-connection-in-pool");
        operation1.get(OP_ADDR).set(address1);
        executeOperation(operation1);
    }

    /**
     * Finding object by JNDI name and checks, if its String representation
     * contains expected substrings
     *
     * @param jndiName of object
     * @param contains - substring, must be contained
     * @throws Exception
     */
    public void testJndiObject(String jndiName, String... contains)
            throws Exception {
        Object o = new InitialContext().lookup(jndiName);
        assertNotNull(o);
        for (String c : contains) {
            assertTrue(o.toString() + " should contain " + c, o.toString()
                    .contains(c));
        }

    }

    /**
     * Checks Set if there is a String element, containing some substring and
     * returns it
     *
     * @param ids     - Set
     * @param contain - substring
     * @return String
     */
    public String getElementContaining(Set<String> ids, String contain) {
        Iterator<String> it = ids.iterator();
        while (it.hasNext()) {
            String t = it.next();
            if (t.contains(contain)) {
                return t;
            }
        }
        return null;
    }

}
