/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2011 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library 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 any later version.
 *
 * This library 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 library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id:RegistryServiceImpl.java 10372 2007-05-14 13:58:42Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.configadmin.internal;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Collections;
import java.util.Dictionary;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.osgi.framework.ServiceReference;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.ow2.jonas.configadmin.ConfigurationInfo;
import org.ow2.jonas.configadmin.internal.generic.DefaultConfigurationAdapterRegistry;
import org.ow2.util.archive.api.IFileArchive;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.ErrorHandler;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isNotNull;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertTrue;

public class ConfigAdminDeployerTestCase {

    private ConfigAdminDeployer deployer;

    @Mock
    private ConfigurationAdmin ca;

    @Mock
    private Configuration configuration;

    @Mock
    private Configuration factoryConfiguration;

    @Mock
    private ServiceReference ref;


    @BeforeMethod
    public void setUp() throws Exception {

        MockitoAnnotations.initMocks(this);

        deployer = new ConfigAdminDeployer();
        deployer.bindConfigurationAdmin(ca);
        deployer.validate();

        // Register the registry
        when(ref.getProperty(eq("namespace"))).thenReturn(ConfigAdminDeployable.NAMESPACE);
        DefaultConfigurationAdapterRegistry registry = new DefaultConfigurationAdapterRegistry();
        deployer.bindXmlConfigurationAdapterRegistry(registry, ref);
    }

    @Test
    public void testParsingInvalidSchemaLocation() throws Exception {

        ConfigAdminDeployable deployable = mockDeployable("/invalid-schema-location.xml");

        when(ca.getConfiguration(anyString(), anyString())).thenReturn(configuration);

        deployer.deploy(deployable);

        verify(configuration).update(any(Dictionary.class));
    }

    @Test
    public void testParsingNoSchemaLocation() throws Exception {

        ConfigAdminDeployable deployable = mockDeployable("/no-schema-location.xml");

        when(ca.getConfiguration(anyString(), anyString())).thenReturn(configuration);

        deployer.deploy(deployable);

        verify(configuration).update(any(Dictionary.class));
    }

    @Test
    public void testOneFactoryConfiguration() throws Exception {

        ConfigAdminDeployable deployable = mockDeployable("/one-factory-configuration.xml");

        when(ca.createFactoryConfiguration(anyString(), anyString())).thenReturn(factoryConfiguration);

        deployer.deploy(deployable);

        verify(factoryConfiguration).update(any(Dictionary.class));
    }

    @Test
    public void testParsingUnsupportedType() throws Exception {

        ConfigAdminDeployable deployable = mockDeployable("/unsupported-element.xml");

        when(ca.listConfigurations(anyString())).thenReturn(null);

        deployer.deploy(deployable);

        verify(ca).listConfigurations(anyString());

        verifyNoMoreInteractions(ca);
    }

    @Test
    public void testUndeployRemoveConfigurations() throws Exception {

        ConfigAdminDeployable deployable = mockDeployable("/deploy-undeploy-configurations.xml");

        // Behaviors
        when(ca.getConfiguration(anyString(), anyString())).thenReturn(configuration);
        when(ca.createFactoryConfiguration(anyString(), anyString())).thenReturn(factoryConfiguration);

        // Execution
        deployer.deploy(deployable);

        // Assertions (Configurations has been pushed)
        verify(configuration).update(any(Dictionary.class));
        verify(factoryConfiguration).update(any(Dictionary.class));

        deployer.undeploy(deployable);

        // Assertions (Configurations has been deleted)
        verify(configuration).delete();
        verify(factoryConfiguration).delete();

    }

    @Test
    public void testDeployedConfigurationsAreRemovedWhenTheAssociatedRegistryDisappear() throws Exception {

        ConfigAdminDeployable deployable = mockDeployable("/deploy-undeploy-configurations.xml");

        // Behaviors
        when(ca.getConfiguration(anyString(), anyString())).thenReturn(configuration);
        when(ca.createFactoryConfiguration(anyString(), anyString())).thenReturn(factoryConfiguration);

        // Execution
        deployer.deploy(deployable);

        // Assertions (Configurations has been pushed)
        verify(configuration).update(any(Dictionary.class));
        verify(factoryConfiguration).update(any(Dictionary.class));

        deployer.unbindXmlConfigurationAdapterRegistry(ref);

        // Assertions (Configurations has been deleted)
        verify(configuration).delete();
        verify(factoryConfiguration).delete();

        DefaultConfigurationAdapterRegistry registry = new DefaultConfigurationAdapterRegistry();
        deployer.bindXmlConfigurationAdapterRegistry(registry, ref);

        verify(configuration,times(2)).update(any(Dictionary.class));
        verify(factoryConfiguration,times(2)).update(any(Dictionary.class));

    }

    @Test
    public void testConfigurationAssociation() throws Exception {
        ConfigurationInfo info = new ConfigurationInfo("JoramTopic", false);
        Element e = getElement("<topic xmlns='http://joram.ow2.org/xmlns' />");

        when(ca.getConfiguration(anyString(), anyString())).thenReturn(configuration);

        ConfigurationItem item = new ConfigurationItem(e);
        item = spy(item);

        ConfigurationAssociationEvent cae = new ConfigurationAssociationEvent(item, Collections.singleton(info));
        deployer.onAssociation(cae);

        verify(item).getConfigurations();
    }

    @Test
    public void testFactoryConfigurationAssociation() throws Exception {
        ConfigurationInfo info = new ConfigurationInfo("JoramTopic", true);
        Element e = getElement("<topic xmlns='http://joram.ow2.org/xmlns' />");

        when(ca.createFactoryConfiguration(anyString(), anyString())).thenReturn(factoryConfiguration);

        ConfigurationItem item = new ConfigurationItem(e);
        item = spy(item);

        ConfigurationAssociationEvent cae = new ConfigurationAssociationEvent(item, Collections.singleton(info));
        deployer.onAssociation(cae);

        verify(item).getConfigurations();
    }

    @Test
    public void testDissociation() throws Exception {
        Element e = getElement("<topic xmlns='http://joram.ow2.org/xmlns' />");
        ConfigurationItem item = new ConfigurationItem(e);
        item.getConfigurations().add(configuration);
        item = spy(item);

        ConfigurationAssociationEvent cae = new ConfigurationAssociationEvent(item, null);
        deployer.onDissociation(cae);

        verify(configuration).delete();

        assertTrue(item.getConfigurations().isEmpty());
        // Check that the deployer tries to associate the item with remaining registries
        verify(item).onAdapterRegistryArrival(any(AdapterRegistryEvent.class));
    }

    private ConfigAdminDeployable mockDeployable(String filename) throws Exception {
        IFileArchive archive = mock(IFileArchive.class);

        ConfigAdminDeployable deployable = new ConfigAdminDeployable(archive);
        deployable = spy(deployable);

        when(deployable.getArchive()).thenReturn(archive);
        when(archive.getURL()).thenReturn(getUrl(filename));

        return deployable;
    }

    private URL getUrl(String name) {
        return getClass().getResource(name);
    }

    private Element getElement(String xml) throws Exception {

        // Transform in InputStream
        ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes());

        // Parse the DOM
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler(mock(ErrorHandler.class));
        Document doc = builder.parse(is);

        return doc.getDocumentElement();
    }

}
