/*
 * Queue - A Queueing system that can be used to handle labs in higher education
 * Copyright (C) 2016-2024  Delft University of Technology
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
package test;

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

import java.util.function.Consumer;
import java.util.function.Predicate;

import org.springframework.test.web.servlet.ResultMatcher;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;

public class JsonContentMatcher<T> {
	private static final ObjectMapper mapper = new ObjectMapper()
			.registerModule(new ParameterNamesModule())
			.registerModule(new Jdk8Module())
			.registerModule(new JavaTimeModule());

	private final Class<T> clazz;

	public JsonContentMatcher(Class<T> clazz) {
		this.clazz = clazz;
	}

	/**
	 * Runs the given consumer on the list of JSON content.
	 *
	 * @param  p The consumer to check the data with.
	 * @return   A ResultMatcher representing the check.
	 */
	public ResultMatcher test(Consumer<T> p) {
		return result -> {
			String json = result.getResponse().getContentAsString();
			T t = mapper.readValue(json, clazz);
			p.accept(t);
		};
	}

	/**
	 * Check whether the given predicate matches on the content of the response.
	 *
	 * @param  p The predicate to check the data with.
	 * @return   A ResultMatcher representing the predicate check.
	 */
	public ResultMatcher predicate(Predicate<T> p) {
		return test(t -> assertThat(p.test(t)).isTrue());
	}

	/**
	 * Check whether the content contains an exact match with the given data.
	 *
	 * @param  t The data to compare to.
	 * @return   A ResultMatcher representing the contains check.
	 */
	public ResultMatcher isEqualTo(T t) {
		return test(o -> assertThat(o).isEqualTo(t));
	}

	/**
	 * Gets a new JsonContentMatcher for the given class.
	 *
	 * @param  clazz The class to convert the JSON to.
	 * @param  <T>   The type of the expected JSON object.
	 * @return       A JsonContentMatcher with the given type.
	 */
	public static <T> JsonContentMatcher<T> jsonContent(Class<T> clazz) {
		return new JsonContentMatcher<>(clazz);
	}
}
