/**
 * 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 (at your option) 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: ConfigurationItemTestCase.java 22135 2012-02-22 10:51:11Z sauthieg $
 * --------------------------------------------------------------------------
 */


package org.ow2.jonas.configadmin.internal;

import java.io.ByteArrayInputStream;
import java.util.Collections;

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

import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.ow2.jonas.configadmin.ConfigurationInfo;
import org.ow2.jonas.configadmin.XmlConfigurationAdapter;
import org.ow2.jonas.configadmin.XmlConfigurationAdapterRegistry;
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.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;

/**
 * A {@code ConfigurationItemTestCase} is ...
 *
 * @author Guillaume Sauthier
 */
public class ConfigurationItemTestCase {

    @Mock
    private ConfigurationAssociationListener associationListener;

    @Mock
    private XmlConfigurationAdapterRegistry registry;

    @Mock
    private XmlConfigurationAdapter adapter;

    private ConfigurationInfo info;
    private ConfigurationItem item;

    @BeforeMethod
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);

        info = new ConfigurationInfo("JoramTopic", true);

        when(registry.getAdapter(eq("topic"))).thenReturn(adapter);
        when(adapter.convert(any(Element.class))).thenReturn(Collections.singleton(info));

        Element e = getElement("<topic xmlns='http://joram.ow2.org/xmlns' />");

        item = new ConfigurationItem(e);
        item.addAssociationListener(associationListener);

    }

    @Test
    public void testAssociationWithRightNamespace() throws Exception {

        AdapterRegistryEvent eventA = new AdapterRegistryEvent(registry, "http://joram.ow2.org/xmlns");
        ConfigurationAssociationEvent cae = new ConfigurationAssociationEvent(item, Collections.singleton(info));

        item.onAdapterRegistryArrival(eventA);

        verify(associationListener).onAssociation(eq(cae));
    }

    @Test
    public void testSecondMatchingRegistryIsNotUsed() throws Exception {

        XmlConfigurationAdapterRegistry second = mock(XmlConfigurationAdapterRegistry.class);

        AdapterRegistryEvent eventA = new AdapterRegistryEvent(registry, "http://joram.ow2.org/xmlns");
        AdapterRegistryEvent eventB = new AdapterRegistryEvent(second, "http://joram.ow2.org/xmlns");
        ConfigurationAssociationEvent cae = new ConfigurationAssociationEvent(item, Collections.singleton(info));

        item.onAdapterRegistryArrival(eventA);
        item.onAdapterRegistryArrival(eventB);

        verify(associationListener).onAssociation(eq(cae));
        verifyZeroInteractions(second);
    }

    @Test
    public void testItemCanBeReAssociatedWithSecondRegistry() throws Exception {

        XmlConfigurationAdapterRegistry second = mock(XmlConfigurationAdapterRegistry.class);
        when(second.getAdapter(eq("topic"))).thenReturn(adapter);

        AdapterRegistryEvent eventA = new AdapterRegistryEvent(registry, "http://joram.ow2.org/xmlns");
        AdapterRegistryEvent eventB = new AdapterRegistryEvent(second, "http://joram.ow2.org/xmlns");
        ConfigurationAssociationEvent cae = new ConfigurationAssociationEvent(item, Collections.singleton(info));
        ConfigurationAssociationEvent cae2 = new ConfigurationAssociationEvent(item, null);

        item.onAdapterRegistryArrival(eventA);
        item.onAdapterRegistryRemoval(eventA);
        item.onAdapterRegistryArrival(eventB);

        verify(associationListener, times(2)).onAssociation(eq(cae));
        verify(associationListener).onDissociation(eq(cae2));
    }

    @Test
    public void testNoAssociationWithWrongNamespace() throws Exception {

        AdapterRegistryEvent eventA = new AdapterRegistryEvent(registry, "http://joram.ow2.org/xmlns/unbound");

        item.onAdapterRegistryArrival(eventA);

        verifyZeroInteractions(registry);
        verifyZeroInteractions(associationListener);
    }

    @Test
    public void testItemCloseWhenAssociated() throws Exception {

        AdapterRegistryEvent eventA = new AdapterRegistryEvent(registry, "http://joram.ow2.org/xmlns");
        ConfigurationAssociationEvent cae = new ConfigurationAssociationEvent(item, Collections.singleton(info));

        item.onAdapterRegistryArrival(eventA);
        item.close();

        verify(associationListener).onAssociation(eq(cae));
        verify(associationListener).onDissociation(any(ConfigurationAssociationEvent.class));
    }

    @Test
    public void testNoItemCloseWhenNotAssociated() throws Exception {

        item.close();
        verifyZeroInteractions(associationListener);
    }

    @Test
    public void testRemovalOfUnusedRegistryDoNotImpactItem() throws Exception {

        XmlConfigurationAdapterRegistry second = mock(XmlConfigurationAdapterRegistry.class);

        AdapterRegistryEvent eventA = new AdapterRegistryEvent(registry, "http://joram.ow2.org/xmlns");
        AdapterRegistryEvent eventB = new AdapterRegistryEvent(second, "http://joram.ow2.org/xmlns");
        ConfigurationAssociationEvent cae = new ConfigurationAssociationEvent(item, Collections.singleton(info));

        item.onAdapterRegistryArrival(eventA);
        item.onAdapterRegistryRemoval(eventB);

        verify(associationListener).onAssociation(eq(cae));
        verifyZeroInteractions(second);
    }

    @Test
    public void testAssociationListenerThrowingRuntimeException() throws Exception {

        AdapterRegistryEvent event = new AdapterRegistryEvent(registry, "http://joram.ow2.org/xmlns");
        ConfigurationAssociationEvent cae = new ConfigurationAssociationEvent(item, Collections.singleton(info));

        // First time, throw an Exception
        // Second call: do nothing
        doThrow(new RuntimeException())
                .doNothing()
                .when(associationListener).onAssociation(eq(cae));

        item.onAdapterRegistryArrival(event);
        assertThat(item.isFailed(), is( true ));

        // re-play the arrival to simulate another registry
        item.onAdapterRegistryArrival(event);
        assertThat(item.isFailed(), is( false ));
    }

    @Test
    public void testXmlAdapterThrowingRuntimeException() throws Exception {

        AdapterRegistryEvent eventA = new AdapterRegistryEvent(registry, "http://joram.ow2.org/xmlns");

        when(adapter.convert(any(Element.class))).thenThrow(new RuntimeException());

        item.onAdapterRegistryArrival(eventA);

        // The adapter thrown an Exception but the execution flow should continue
        // Nevertheless, the Collection of Configurations in the item should be 0
        assertThat(item.getConfigurations().isEmpty(), is( true ));
        assertThat(item.isFailed(), is( true ));

    }

    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();
    }

}
