/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.activemq.network;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.lang.reflect.Field;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import jakarta.jms.MessageProducer;
import jakarta.jms.TemporaryQueue;

import org.apache.activemq.advisory.AdvisorySupport;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnection;
import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.util.Wait;
import org.junit.Test;

/**
 *
 */
public class DynamicallyIncludedDestinationsDuplexNetworkTest extends SimpleNetworkTest {

    @Override
    protected String getLocalBrokerURI() {
        return "org/apache/activemq/network/duplexDynamicIncludedDestLocalBroker.xml";
    }

    @Override
    protected BrokerService createRemoteBroker() throws Exception {
        final BrokerService broker = new BrokerService();
        broker.setBrokerName("remoteBroker");
        broker.addConnector("tcp://localhost:0");
        return broker;
    }

    @Override
    protected void addNetworkConnectors() throws Exception {
        // For duplex test: only one connector from local to remote, with duplex=true
        final URI remoteConnectURI = remoteBroker.getTransportConnectors().get(0).getConnectUri();

        final DiscoveryNetworkConnector localToRemote = new DiscoveryNetworkConnector(
                new URI("static:(" + remoteConnectURI + ")"));
        localToRemote.setName("networkConnector");
        localToRemote.setDuplex(true);
        localToRemote.setDynamicOnly(false);
        localToRemote.setConduitSubscriptions(true);
        localToRemote.setDecreaseNetworkConsumerPriority(false);

        final List<ActiveMQDestination> dynamicallyIncluded = new ArrayList<>();
        dynamicallyIncluded.add(new ActiveMQQueue("include.test.foo"));
        dynamicallyIncluded.add(new ActiveMQTopic("include.test.bar"));
        localToRemote.setDynamicallyIncludedDestinations(dynamicallyIncluded);

        final List<ActiveMQDestination> excluded = new ArrayList<>();
        excluded.add(new ActiveMQQueue("exclude.test.foo"));
        excluded.add(new ActiveMQTopic("exclude.test.bar"));
        localToRemote.setExcludedDestinations(excluded);

        localBroker.addNetworkConnector(localToRemote);
        localBroker.startNetworkConnector(localToRemote, null);
    }

    // we have to override this, because with dynamicallyIncludedDestinations working properly
    // (see https://issues.apache.org/jira/browse/AMQ-4209) you can't get request/response
    // with temps working (there is no wild card like there is for staticallyIncludedDest)
    //
    @Override
    public void testRequestReply() throws Exception {

    }

    @Test
    public void testTempQueues() throws Exception {
        final TemporaryQueue temp = localSession.createTemporaryQueue();
        final MessageProducer producer = localSession.createProducer(temp);
        producer.send(localSession.createTextMessage("test"));
        assertTrue("Destination created on remote",
            Wait.waitFor(() -> remoteBroker.getAdminView().getTemporaryQueues().length == 1, 5000, 100));
        temp.delete();
        assertTrue("Destination deleted on remote",
            Wait.waitFor(() -> remoteBroker.getAdminView().getTemporaryQueues().length == 0, 5000, 100));
    }

    @Test(timeout = 60 * 1000)
    public void testDynamicallyIncludedDestinationsForDuplex()  throws Exception{
        // Once the bridge is set up, we should see the filter used for the duplex end of the bridge
        // only subscribe to the specific destinations included in the <dynamicallyIncludedDestinations> list
        // so let's test that the filter is correct, let's also test the subscription on the localbroker
        // is correct

        // the bridge on the remote broker has the correct filter
        final TransportConnection bridgeConnection = getDuplexBridgeConnectionFromRemote();
        assertNotNull(bridgeConnection);
        final DemandForwardingBridge duplexBridge = waitForDuplexBridge(bridgeConnection);
        assertNotNull(duplexBridge);
        final NetworkBridgeConfiguration configuration = getConfigurationFromNetworkBridge(duplexBridge);
        assertNotNull(configuration);
        assertFalse("This destinationFilter does not include ONLY the destinations specified in dynamicallyIncludedDestinations",
                configuration.getDestinationFilter().equals(AdvisorySupport.CONSUMER_ADVISORY_TOPIC_PREFIX + ">"));
        assertEquals("There are other patterns in the destinationFilter that shouldn't be there",
                "ActiveMQ.Advisory.Consumer.Queue.include.test.foo,ActiveMQ.Advisory.Consumer.Topic.include.test.bar",
                configuration.getDestinationFilter());
    }

    private NetworkBridgeConfiguration getConfigurationFromNetworkBridge(final DemandForwardingBridgeSupport duplexBridge) throws NoSuchFieldException, IllegalAccessException {
        final Field f = DemandForwardingBridgeSupport.class.getDeclaredField("configuration");
        f.setAccessible(true);
        return (NetworkBridgeConfiguration) f.get(duplexBridge);
    }

    private DemandForwardingBridge getDuplexBridgeFromConnection(final TransportConnection bridgeConnection) throws NoSuchFieldException, IllegalAccessException {
        final Field f = TransportConnection.class.getDeclaredField("duplexBridge");
        f.setAccessible(true);
        return (DemandForwardingBridge) f.get(bridgeConnection);
    }

    private DemandForwardingBridge waitForDuplexBridge(final TransportConnection bridgeConnection) throws Exception {
        assertTrue("Timed out waiting for duplex bridge to be fully started",
                Wait.waitFor(() -> {
                    final DemandForwardingBridge bridge = getDuplexBridgeFromConnection(bridgeConnection);
                    return bridge != null && bridge.getRemoteBrokerName() != null;
                }));
        return getDuplexBridgeFromConnection(bridgeConnection);
    }

    public TransportConnection getDuplexBridgeConnectionFromRemote() throws Exception {
        final TransportConnector transportConnector = remoteBroker.getTransportConnectorByScheme("tcp");
        assertTrue("Timed out waiting for duplex bridge connection",
                Wait.waitFor(() -> !transportConnector.getConnections().isEmpty()));
        return transportConnector.getConnections().get(0);
    }

    @Override
    protected void assertNetworkBridgeStatistics(final long expectedLocalSent, final long expectedRemoteSent) throws Exception {

        final NetworkBridge localBridge = localBroker.getNetworkConnectors().get(0).activeBridges().iterator().next();

        assertTrue(Wait.waitFor(() ->
                expectedLocalSent == localBridge.getNetworkBridgeStatistics().getDequeues().getCount() &&
                expectedRemoteSent == localBridge.getNetworkBridgeStatistics().getReceivedCount().getCount()));

    }
}
