/*
 * JBoss, Home of Professional Open Source.
 *
 * Copyright 2021 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed 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.wildfly.test.manual.observability.opentelemetry;

import static org.jboss.as.test.shared.integration.ejb.security.PermissionUtils.createPermissionsXmlAsset;

import java.io.FilePermission;
import java.net.SocketPermission;
import java.security.SecurityPermission;

import javax.inject.Inject;
import javax.management.MBeanPermission;
import javax.management.MBeanServerPermission;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;

import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.trace.Tracer;
import org.jboss.arquillian.container.test.api.ContainerController;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.test.shared.TestSuiteEnvironment;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(Arquillian.class)
public class BasicOpenTelemetryTestCase {
    public static final String BASIC_OTEL_TEST = "basic";
    private static final String CONTAINER_NAME = "microprofile";

    @ArquillianResource
    private static Deployer deployer;

    @ArquillianResource
    private static ContainerController containerController;

    @Inject
    private Tracer tracer;

    @Inject
    private OpenTelemetry openTelemetry;

    @Deployment(name = BASIC_OTEL_TEST, managed = false)
    public static WebArchive deploy() {
        return ShrinkWrap.create(WebArchive.class, BasicOpenTelemetryTestCase.class.getSimpleName() + ".war")
                .addAsManifestResource(createPermissionsXmlAsset(
                        // Required for the ClientBuilder.newBuilder() so the ServiceLoader will work
                        new FilePermission("<<ALL FILES>>", "read"),
                        // Required for com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider. During <init> there is a
                        // reflection test to check for JAXRS 2.0.
                        new RuntimePermission("accessDeclaredMembers"),
                        // Required for the client to connect
                        new SocketPermission(TestSuiteEnvironment.getHttpAddress() + ":" +
                                TestSuiteEnvironment.getHttpPort(), "connect,resolve"),
                        new SecurityPermission("insertProvider"),
                        new MBeanServerPermission("createMBeanServer"),
                        new MBeanPermission("*", "registerMBean, unregisterMBean, invoke"),
                        new RuntimePermission("getClassLoader"),
                        new RuntimePermission("modifyThread"),
                        new RuntimePermission("setContextClassLoader")
                ), "permissions.xml")
                .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
    }

    @Before
    public void setup() {
        if (!containerController.isStarted(CONTAINER_NAME)) {
            containerController.start(CONTAINER_NAME);
            deployer.deploy(BASIC_OTEL_TEST);
        }
    }

    @AfterClass
    public static void tearDown() throws Exception {
        deployer.undeploy(BASIC_OTEL_TEST);
        containerController.stop(CONTAINER_NAME);
    }

    @Test
    public void hasDefaultInjectedOpenTelemetry() {
        System.out.printf("%nhasDefaultInjectedOpenTelemetry: %s%n%n", openTelemetry);
        Assert.assertNotNull(openTelemetry);
    }

    @Test
    public void hasDefaultInjectedTracer() {
        System.out.printf("%nhasDefaultInjectedTracer: %s%n%n", tracer);
        Assert.assertNotNull(tracer);
    }

    @Test
    public void restClientHasFilterAdded() {
        System.out.println("\nrestClientHasFilterAdded\n");
        Client client = ClientBuilder.newClient();
        org.wildfly.common.Assert.assertTrue(client.getConfiguration().getClasses().stream()
                .map(c -> c.getCanonicalName())
                .anyMatch(n -> "org.wildfly.extension.opentelemetry.api.OpenTelemetryClientRequestFilter".equals(n)));
        client.close();
    }
}
