package org.gcube.application.geoportal.client;

import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.gcube.application.geoportal.client.utils.Serialization;
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.rest.UseCaseDescriptorsI;
import org.gcube.common.clients.delegates.ProxyDelegate;

import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import java.rmi.RemoteException;
import java.util.Iterator;

@RequiredArgsConstructor
@Slf4j
public class UseCaseDescriptors implements UseCaseDescriptorsI {

    @NonNull
    private final ProxyDelegate<WebTarget> delegate;


    @Override
    public UseCaseDescriptor create(Document toCreate) throws RemoteException {
        throw new RuntimeException("Yet To Implement");
    }

    @Override
    public Iterator<UseCaseDescriptor> query(QueryRequest request) throws Exception {
       String json = delegate.make(webTarget ->
               ResponseCommons.check(webTarget.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);
       }
    }

    @Override
    public void deleteById(String id, boolean force) throws RemoteException {
        throw new RuntimeException("Yet To Implement");
    }

    @Override
    public UseCaseDescriptor update(String ID, Document toSet) throws RemoteException {
        throw new RuntimeException("Yet To Implement");
    }

    @Override
    public UseCaseDescriptor getById(String id) throws Exception {
        return delegate.make(webTarget -> ResponseCommons.check(webTarget.path(id).
                request(MediaType.APPLICATION_JSON_TYPE).get(),UseCaseDescriptor.class));
    }
}
