package org.gcube.application.geoportal.service;

import lombok.extern.slf4j.Slf4j;
import org.gcube.application.cms.caches.Engine;
import org.gcube.application.cms.implementations.ImplementationProvider;
import org.gcube.application.cms.serialization.Serialization;
import org.gcube.application.cms.tests.TestProfiles;
import org.gcube.application.cms.tests.TokenSetter;
import org.gcube.application.geoportal.common.utils.tests.GCubeTest;
import org.gcube.application.geoportal.service.engine.providers.ucd.LocalFolderProfileMapCache;
import org.gcube.application.geoportal.service.engine.providers.ucd.ProfileMap;
import org.gcube.application.geoportal.service.rest.GuardedMethod;
import org.glassfish.jersey.test.JerseyTest;
import org.junit.AfterClass;
import org.junit.BeforeClass;

import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;
import java.util.Collections;
import java.util.Map;

@Slf4j
public class BasicServiceTestUnit extends JerseyTest {

	protected static Boolean USE_LOCAL_FOLDER=false;


	@Override
	protected Application configure() {
		return new GeoPortalService(){
			@Override
			public Map<Engine<?>, Class<?>> customImplementations() {
				if(USE_LOCAL_FOLDER)
				return Collections.singletonMap((Engine<ProfileMap>)
						new LocalFolderProfileMapCache(TestProfiles.BASE_FOLDER.getAbsolutePath()),ProfileMap.class);
				else return Collections.emptyMap();
			}

		};
	}

	// Loads UCDs from local folder


	@BeforeClass
	public static void init() {
		GuardedMethod.addPreoperation(new Runnable() {
			@Override
			public void run() {

				String context = GCubeTest.getContext();
				log.debug("TEST IMPL : Setting context "+context+" in received call");
				TokenSetter.set(context);
			}
		});

	}
	@AfterClass
	public static void shutdown(){
		ImplementationProvider.get().shutdownEngines();
	}
	
	protected static<T> T check(Response resp, Class<T> clazz) throws Exception {
		String resString=resp.readEntity(String.class);
		if(resp.getStatus()<200||resp.getStatus()>=300)
			throw new Exception("RESP STATUS IS "+resp.getStatus()+". Message : "+resString);
		log.debug("Resp String is "+resString);
		if(clazz!=null)
			if (clazz==String.class)
				return (T) resString;
			else
				return Serialization.read(resString, clazz);
		else return null;
	}
}
