package org.gcube.application.geoportal.service.engine.providers.ucd;

import org.gcube.application.cms.tests.TestProfiles;
import org.gcube.application.cms.tests.TokenSetter;
import org.gcube.application.geoportal.common.model.rest.ConfigurationException;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.UseCaseDescriptor;
import org.gcube.application.geoportal.common.utils.tests.GCubeTest;
import org.junit.BeforeClass;
import org.junit.Test;

import javax.xml.bind.JAXBException;
import java.util.Arrays;
import java.util.Map;

import static junit.framework.TestCase.*;
import static org.junit.Assume.assumeTrue;

public class UCDLoadingTest {

    @BeforeClass
    public static void initProvider() throws JAXBException {
        SingleISResourceUCDProvider.directInit();
    }

    @Test
    public void testSerializaion() throws JAXBException {
        SingleISResourceUCDProvider.ISBean bean = new SingleISResourceUCDProvider.ISBean();
        bean.setRecords(Arrays.asList(
                new SingleISResourceUCDProvider.ISBean.Record("Human readable name","some url","[opt] regex"),
                new SingleISResourceUCDProvider.ISBean.Record("Another readable name","some other url","[opt] regex")));
        String xml = SingleISResourceUCDProvider.write(bean);
        System.out.println("XML is "+xml);
        SingleISResourceUCDProvider.ISBean reloaded =SingleISResourceUCDProvider.read(xml);
        assertEquals(bean,reloaded);
    }

    @Test
    public void testLoadingFromIS() throws ConfigurationException {
        assumeTrue(GCubeTest.isTestInfrastructureEnabled());
        TokenSetter.set(GCubeTest.getContext());
        SingleISResourceUCDProvider provider = new SingleISResourceUCDProvider();
        ProfileMap map = provider.getObject();
        map.forEach((s, useCaseDescriptor) -> {
            System.out.println("Checking "+s);
            assertNotNull(useCaseDescriptor);
            assertNotNull(useCaseDescriptor.getId());
            assertNull(useCaseDescriptor.getMongoId());
            assertNotNull(useCaseDescriptor.getDataAccessPolicies());
            assertNotNull(useCaseDescriptor.getHandlers());
        });
        System.out.println("UCIDs IN "+GCubeTest.getContext()+": "+map.keySet());
    }

    @Test
    public void testLocalLoading() throws ConfigurationException {
        Map<String, UseCaseDescriptor> liveMap=new LocalFolderProfileMapCache(TestProfiles.BASE_FOLDER.getAbsolutePath()).retrieveObject(null);
        assertTrue(liveMap.size()>0);
        liveMap.forEach((s, useCaseDescriptor) -> {
            System.out.println("Checking "+s);
            assertNotNull(useCaseDescriptor);
            assertNotNull(useCaseDescriptor.getId());
            assertNotNull(useCaseDescriptor.getDataAccessPolicies());
            assertNotNull(useCaseDescriptor.getHandlers());
        });
    }
}
