package org.gcube.application.geoportal.service.rest;


import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import lombok.extern.slf4j.Slf4j;
import org.gcube.application.cms.implementations.ImplementationProvider;
import org.gcube.application.cms.plugins.Plugin;
import org.gcube.application.geoportal.common.model.plugins.PluginDescriptor;
import org.gcube.application.geoportal.common.rest.InterfaceConstants;
import org.gcube.application.geoportal.service.engine.providers.PluginManager;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Path(InterfaceConstants.Methods.PLUGINS)
@Slf4j
@RequestHeaders({
        @RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
        @RequestHeader( name = "Content-Type", description = "application/json")
})
public class Plugins {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<PluginDescriptor> getDescriptor(){
        return new GuardedMethod<List<PluginDescriptor>>(){
            @Override
            protected List<PluginDescriptor> run() throws Exception, WebApplicationException {
                List<PluginDescriptor> toReturn=new ArrayList<>();
                ImplementationProvider.get().getProvidedObjectByClass(PluginManager.PluginMap.class).
                        forEach((s, plugin) -> {try {
                            toReturn.add(plugin.getDescriptor());
                        }catch (Throwable t){ log.error("Unable to get Descriptor for {}",s,t);}});
                return toReturn;
            }
        }.execute().getResult();
    }

    @GET
    @Path("{pluginID}")
    @Produces(MediaType.APPLICATION_JSON)
    public PluginDescriptor getDescriptorByID(@PathParam("pluginID") String pluginID){
        return new GuardedMethod<PluginDescriptor>(){
            @Override
            protected PluginDescriptor run() throws Exception, WebApplicationException {
                Map<String, Plugin> m=ImplementationProvider.get().getProvidedObjectByClass(PluginManager.PluginMap.class);
                if(m.containsKey(pluginID))
                    return m.get(pluginID).getDescriptor();
                else throw new WebApplicationException("Plugin \""+pluginID+"\" not found", Response.Status.NOT_FOUND);
            }
        }.execute().getResult();
    }

}
