package org.gcube.application.geoportal.service.engine.profiles;

import org.bson.Document;
import org.gcube.application.cms.serialization.Serialization;
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.gcube.application.geoportal.service.BasicServiceTestUnit;
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 javax.ws.rs.core.Response;
import java.util.List;

import static junit.framework.Assert.fail;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assume.assumeTrue;

public class UCDCalls extends BasicServiceTestUnit {


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

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

    @Test
    public void queryByHandlerId() throws Exception {

        QueryRequest req = new QueryRequest();
        req.setFilter(Document.parse("{\"_handlers._id\" : {\"$eq\" : \"org.gcube....geoportal-data-entry-portlet\"}}"));
        check(baseTarget().path(InterfaceConstants.Methods.QUERY_PATH).request(MediaType.APPLICATION_JSON_TYPE).
                post(Entity.entity(Serialization.write(req),MediaType.APPLICATION_JSON)), List.class);
    }

    @Test
    public void getById() throws Exception {
        List result=check(baseTarget().path(InterfaceConstants.Methods.QUERY_PATH).request(MediaType.APPLICATION_JSON_TYPE).
                post(Entity.entity(Serialization.write(new QueryRequest()),MediaType.APPLICATION_JSON)), List.class);

        assertTrue("Existing UCDs : ",result.size()>0);
        result.forEach(c->{
            try{
                UseCaseDescriptor d= Serialization.convert(c,UseCaseDescriptor.class);
                check(baseTarget().path(d.getId()).request(MediaType.APPLICATION_JSON_TYPE).get(), UseCaseDescriptor.class);
            } catch (Exception e) {
                e.printStackTrace(System.err);
                fail(e.getMessage());
            }
        });
    }

    @Test

    public void getByWrongID() throws Exception {
        String testProfileId="gnegne";
        assertEquals(baseTarget().path(testProfileId).request(MediaType.APPLICATION_JSON_TYPE).get().getStatus(), Response.Status.NOT_FOUND.getStatusCode());
    }

}
