/*
 * Copyright 2012-2017 the original author or authors.
 *
 * 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.springframework.boot.endpoint;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.util.ReflectionUtils;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link AnnotationEndpointDiscoverer}.
 *
 * @author Andy Wilkinson
 * @author Stephane Nicoll
 */
public class AnnotationEndpointDiscovererTests {

	@Rule
	public final ExpectedException thrown = ExpectedException.none();

	@Test
	public void discoverWorksWhenThereAreNoEndpoints() {
		load(EmptyConfiguration.class,
				(context) -> assertThat(new TestAnnotationEndpointDiscoverer(context)
						.discoverEndpoints().isEmpty()));
	}

	@Test
	public void endpointIsDiscovered() {
		load(TestEndpointConfiguration.class, (context) -> {
			Map<String, EndpointInfo<TestEndpointOperation>> endpoints = mapEndpoints(
					new TestAnnotationEndpointDiscoverer(context).discoverEndpoints());
			assertThat(endpoints).containsOnlyKeys("test");
			Map<Method, TestEndpointOperation> operations = mapOperations(
					endpoints.get("test"));
			assertThat(operations).hasSize(3);
			assertThat(operations).containsKeys(
					ReflectionUtils.findMethod(TestEndpoint.class, "getAll"),
					ReflectionUtils.findMethod(TestEndpoint.class, "getOne",
							String.class),
					ReflectionUtils.findMethod(TestEndpoint.class, "update", String.class,
							String.class));
		});
	}

	@Test
	public void subclassedEndpointIsDiscovered() {
		load(TestEndpointSubclassConfiguration.class, (context) -> {
			Map<String, EndpointInfo<TestEndpointOperation>> endpoints = mapEndpoints(
					new TestAnnotationEndpointDiscoverer(context).discoverEndpoints());
			assertThat(endpoints).containsOnlyKeys("test");
			Map<Method, TestEndpointOperation> operations = mapOperations(
					endpoints.get("test"));
			assertThat(operations).hasSize(4);
			assertThat(operations).containsKeys(
					ReflectionUtils.findMethod(TestEndpoint.class, "getAll"),
					ReflectionUtils.findMethod(TestEndpoint.class, "getOne",
							String.class),
					ReflectionUtils.findMethod(TestEndpoint.class, "update", String.class,
							String.class),
					ReflectionUtils.findMethod(TestEndpointSubclass.class,
							"updateWithMoreArguments", String.class, String.class,
							String.class));
		});
	}

	@Test
	public void discoveryFailsWhenTwoEndpointsHaveTheSameId() {
		load(ClashingEndpointConfiguration.class, (context) -> {
			this.thrown.expect(IllegalStateException.class);
			this.thrown.expectMessage("Found two endpoints with the id 'test': ");
			new TestAnnotationEndpointDiscoverer(context).discoverEndpoints();
		});
	}

	@Test
	public void endpointMainReadOperationIsNotCachedWithTtlSetToZero() {
		load(TestEndpointConfiguration.class, (context) -> {
			Map<String, EndpointInfo<TestEndpointOperation>> endpoints = mapEndpoints(
					new TestAnnotationEndpointDiscoverer(context,
							(endpointId) -> new CachingConfiguration(0))
									.discoverEndpoints());
			assertThat(endpoints).containsOnlyKeys("test");
			Map<Method, TestEndpointOperation> operations = mapOperations(
					endpoints.get("test"));
			assertThat(operations).hasSize(3);
			operations.values()
					.forEach(operation -> assertThat(operation.getOperationInvoker())
							.isNotInstanceOf(CachingOperationInvoker.class));
		});
	}

	@Test
	public void endpointMainReadOperationIsNotCachedWithNonMatchingId() {
		Function<String, CachingConfiguration> cachingConfigurationFactory = (
				endpointId) -> (endpointId.equals("foo") ? new CachingConfiguration(500)
						: new CachingConfiguration(0));
		load(TestEndpointConfiguration.class, (context) -> {
			Map<String, EndpointInfo<TestEndpointOperation>> endpoints = mapEndpoints(
					new TestAnnotationEndpointDiscoverer(context,
							cachingConfigurationFactory).discoverEndpoints());
			assertThat(endpoints).containsOnlyKeys("test");
			Map<Method, TestEndpointOperation> operations = mapOperations(
					endpoints.get("test"));
			assertThat(operations).hasSize(3);
			operations.values()
					.forEach(operation -> assertThat(operation.getOperationInvoker())
							.isNotInstanceOf(CachingOperationInvoker.class));
		});
	}

	@Test
	public void endpointMainReadOperationIsCachedWithMatchingId() {
		Function<String, CachingConfiguration> cachingConfigurationFactory = (
				endpointId) -> (endpointId.equals("test") ? new CachingConfiguration(500)
						: new CachingConfiguration(0));
		load(TestEndpointConfiguration.class, (context) -> {
			Map<String, EndpointInfo<TestEndpointOperation>> endpoints = mapEndpoints(
					new TestAnnotationEndpointDiscoverer(context,
							cachingConfigurationFactory).discoverEndpoints());
			assertThat(endpoints).containsOnlyKeys("test");
			Map<Method, TestEndpointOperation> operations = mapOperations(
					endpoints.get("test"));
			OperationInvoker getAllOperationInvoker = operations
					.get(ReflectionUtils.findMethod(TestEndpoint.class, "getAll"))
					.getOperationInvoker();
			assertThat(getAllOperationInvoker)
					.isInstanceOf(CachingOperationInvoker.class);
			assertThat(((CachingOperationInvoker) getAllOperationInvoker).getTimeToLive())
					.isEqualTo(500);
			assertThat(operations.get(ReflectionUtils.findMethod(TestEndpoint.class,
					"getOne", String.class)).getOperationInvoker())
							.isNotInstanceOf(CachingOperationInvoker.class);
			assertThat(operations.get(ReflectionUtils.findMethod(TestEndpoint.class,
					"update", String.class, String.class)).getOperationInvoker())
							.isNotInstanceOf(CachingOperationInvoker.class);
		});
	}

	private Map<String, EndpointInfo<TestEndpointOperation>> mapEndpoints(
			Collection<EndpointInfo<TestEndpointOperation>> endpoints) {
		Map<String, EndpointInfo<TestEndpointOperation>> endpointById = new LinkedHashMap<>();
		endpoints.forEach((endpoint) -> {
			EndpointInfo<TestEndpointOperation> existing = endpointById
					.put(endpoint.getId(), endpoint);
			if (existing != null) {
				throw new AssertionError(String.format(
						"Found endpoints with duplicate id '%s'", endpoint.getId()));
			}
		});
		return endpointById;
	}

	private Map<Method, TestEndpointOperation> mapOperations(
			EndpointInfo<TestEndpointOperation> endpoint) {
		Map<Method, TestEndpointOperation> operationByMethod = new HashMap<>();
		endpoint.getOperations().forEach((operation) -> {
			EndpointOperation existing = operationByMethod
					.put(operation.getOperationMethod(), operation);
			if (existing != null) {
				throw new AssertionError(String.format(
						"Found endpoint with duplicate operation method '%s'",
						operation.getOperationMethod()));
			}
		});
		return operationByMethod;
	}

	private void load(Class<?> configuration,
			Consumer<AnnotationConfigApplicationContext> consumer) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
				configuration);
		try {
			consumer.accept(context);
		}
		finally {
			context.close();
		}
	}

	@Configuration
	static class EmptyConfiguration {

	}

	@Endpoint(id = "test")
	static class TestEndpoint {

		@ReadOperation
		public Object getAll() {
			return null;
		}

		@ReadOperation
		public Object getOne(@Selector String id) {
			return null;
		}

		@WriteOperation
		public void update(String foo, String bar) {

		}

		public void someOtherMethod() {

		}

	}

	static class TestEndpointSubclass extends TestEndpoint {

		@WriteOperation
		public void updateWithMoreArguments(String foo, String bar, String baz) {

		}

	}

	@Configuration
	static class TestEndpointConfiguration {

		@Bean
		public TestEndpoint testEndpoint() {
			return new TestEndpoint();
		}

	}

	@Configuration
	static class TestEndpointSubclassConfiguration {

		@Bean
		public TestEndpointSubclass testEndpointSubclass() {
			return new TestEndpointSubclass();
		}

	}

	@Configuration
	static class ClashingEndpointConfiguration {

		@Bean
		public TestEndpoint testEndpointTwo() {
			return new TestEndpoint();
		}

		@Bean
		public TestEndpoint testEndpointOne() {
			return new TestEndpoint();
		}
	}

	private static final class TestEndpointOperation extends EndpointOperation {

		private final Method operationMethod;

		private TestEndpointOperation(EndpointOperationType type,
				OperationInvoker operationInvoker, Method operationMethod) {
			super(type, operationInvoker, true);
			this.operationMethod = operationMethod;
		}

		private Method getOperationMethod() {
			return this.operationMethod;
		}

	}

	private static class TestAnnotationEndpointDiscoverer
			extends AnnotationEndpointDiscoverer<TestEndpointOperation, Method> {

		TestAnnotationEndpointDiscoverer(ApplicationContext applicationContext,
				Function<String, CachingConfiguration> cachingConfigurationFactory) {
			super(applicationContext, endpointOperationFactory(),
					TestEndpointOperation::getOperationMethod,
					cachingConfigurationFactory);
		}

		TestAnnotationEndpointDiscoverer(ApplicationContext applicationContext) {
			this(applicationContext, (id) -> null);
		}

		@Override
		public Collection<EndpointInfo<TestEndpointOperation>> discoverEndpoints() {
			return discoverEndpointsWithExtension(null, null).stream()
					.map(EndpointInfoDescriptor::getEndpointInfo)
					.collect(Collectors.toList());
		}

		private static EndpointOperationFactory<TestEndpointOperation> endpointOperationFactory() {
			return new EndpointOperationFactory<TestEndpointOperation>() {

				@Override
				public TestEndpointOperation createOperation(String endpointId,
						AnnotationAttributes operationAttributes, Object target,
						Method operationMethod, EndpointOperationType operationType,
						long timeToLive) {
					return new TestEndpointOperation(operationType,
							createOperationInvoker(timeToLive), operationMethod);
				}

				private OperationInvoker createOperationInvoker(long timeToLive) {
					OperationInvoker invoker = (arguments) -> null;
					if (timeToLive > 0) {
						return new CachingOperationInvoker(invoker, timeToLive);
					}
					else {
						return invoker;
					}
				}
			};
		}

	}

}
