package org.gcube.application.geoportal.service;

import lombok.extern.slf4j.Slf4j;
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.model.rest.QueryRequest;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.UseCaseDescriptor;
import org.gcube.application.geoportal.common.rest.InterfaceConstants;
import org.gcube.application.geoportal.common.utils.tests.GCubeTest;
import org.junit.Before;
import org.junit.Test;

import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import java.util.Iterator;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicLong;

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

@Slf4j
public class UCDTests extends BasicServiceTestUnit{

    @Before
    public void setContext(){
        assumeTrue(GCubeTest.isTestInfrastructureEnabled());
        TokenSetter.set(GCubeTest.getContext());
    }


    protected WebTarget baseTarget(){
        return super.target(InterfaceConstants.Methods.UCD);
    }


    private Iterator<UseCaseDescriptor> query(QueryRequest request) throws Exception {
        String json = check(baseTarget().path(InterfaceConstants.Methods.QUERY_PATH).
                                request(MediaType.APPLICATION_JSON).post(Entity.entity(request,MediaType.APPLICATION_JSON)),
                        String.class);
        try{
            return Serialization.readCollection(json, UseCaseDescriptor.class);
        }catch(Throwable t){
            log.error("Unable to query UCD with {} ",request,t);
            throw new Exception("Unable to parse collection. Check projection settings.",t);
        }
    }

    @Test
    public void queryAll() throws Exception {
        QueryRequest request=new QueryRequest();
        AtomicLong l = new AtomicLong();
        query(request).forEachRemaining(u->l.incrementAndGet());
        assertTrue(l.get()>0);
    }


    @Test
    public void registerNew() throws Exception {
        UseCaseDescriptor randomUCD=TestProfiles.profiles.get("basic");
        randomUCD.setId(UUID.randomUUID().toString());
        randomUCD.setName("Test UCD");
        randomUCD.setMongoId(null);

        UseCaseDescriptor ucd =check(baseTarget().request(MediaType.APPLICATION_JSON).
                post(Entity.entity(Serialization.write(randomUCD),
                        MediaType.APPLICATION_JSON)), UseCaseDescriptor.class);

    }
}
