package eu.dnetlib.openaire.dsm;

import static java.util.Collections.singletonList;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.core.Is.is;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.nio.charset.Charset;
import java.util.List;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

import eu.dnetlib.enabling.datasources.common.DsmException;
import eu.dnetlib.openaire.dsm.dao.utils.DsmMappingUtils;
import eu.dnetlib.openaire.dsm.domain.db.DatasourceDbEntry;
import eu.dnetlib.openaire.exporter.model.dsm.DatasourceDetails;
import eu.dnetlib.openaire.exporter.model.vocabularies.Country;

@SpringBootTest
@WebMvcTest(DsmApiController.class)
public class DatasourceApiControllerTest {

	public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(
		MediaType.APPLICATION_JSON.getType(),
		MediaType.APPLICATION_JSON.getSubtype(),
		Charset.forName("utf8"));

	@Autowired
	private MockMvc mvc;

	@MockBean
	private DsmApiController dsController;

	@Test
	// @Disabled
	public void listCountries() throws Exception {
		final Country c = new Country("it", "Italy");
		final List<Country> countries = singletonList(c);

		given(dsController.listCountries()).willReturn(countries);

		mvc.perform(get("/ds/countries")
			.contentType(APPLICATION_JSON_UTF8))
			.andExpect(status().isOk())
			.andExpect(jsonPath("$", hasSize(1)))
			.andExpect(jsonPath("$[0].code", is(c.getCode())))
			.andExpect(jsonPath("$[0].name", is(c.getName())));
	}

	@Test
	public void testAddDs() throws DsmException {
		final DatasourceDetails dd = new DatasourceDetails().setId("openaire____::issn19718357")
			.setIssn("1971-8357")
			.setNamespaceprefix("19718357____");

		final DatasourceDbEntry datasourceDbEntry = DsmMappingUtils.asDbEntry(dd);
		System.out.println(datasourceDbEntry.getIssn());

	}

}
