package eu.dnetlib.wds.nodes;

import com.google.gson.Gson;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.enabling.resultset.client.ResultSetClient;
import eu.dnetlib.msro.workflows.graph.Arc;
import eu.dnetlib.msro.workflows.nodes.SimpleJobNode;
import eu.dnetlib.msro.workflows.procs.Env;
import eu.dnetlib.rmi.common.ResultSet;
import eu.dnetlib.rmi.enabling.ISLookUpService;
import eu.dnetlib.rmi.enabling.ISRegistryService;
import eu.dnetlib.wds.collector.plugins.GenericDatasource;
import org.antlr.stringtemplate.StringTemplate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;

import java.util.List;

public class SaveRepositoryProfileJobNode extends SimpleJobNode {

    final static String query = "for $x in collection('/db/DRIVER/RepositoryServiceResources/RepositoryServiceResourceType') where $x//DATASOURCE_ORIGINAL_ID/text() ='%s' return $x//RESOURCE_IDENTIFIER/@value/string()";

    private static final Log log = LogFactory.getLog(SaveRepositoryProfileJobNode.class);

    @Autowired
    private UniqueServiceLocator serviceLocator;

    private String inputEprParam;

    @Autowired
    private ResultSetClient resultSetClient;


    private StringTemplate xmlTemplate;

    @Override
    protected String execute(Env env) throws Exception {

        final ISRegistryService registryService = serviceLocator.getService(ISRegistryService.class);

        final ISLookUpService lookUpService = serviceLocator.getService(ISLookUpService.class);

        final ResultSet<?> rsIn = env.getAttribute(inputEprParam, ResultSet.class);
        final Iterable<String> profiles = resultSetClient.iter(rsIn, String.class);
        final Gson g = new Gson();
        if (profiles != null) {
            profiles.forEach(it -> {
                final GenericDatasource ds = g.fromJson(it, GenericDatasource.class);
                xmlTemplate.removeAttribute("datasource");
                xmlTemplate.setAttribute("datasource", ds);
                final String currentProfile = xmlTemplate.toString();
                try {
                    final List<String> resourceIds = lookUpService.quickSearchProfile(String.format(query, ds.getId()));
                    if (resourceIds != null && resourceIds.size() > 0) {
                        registryService.updateProfile(resourceIds.get(0), currentProfile, "RepositoryServiceResourceType");
                    } else
                        registryService.registerProfile(currentProfile);
                } catch (Exception e) {
                    log.error("Error on saving profile " + it, e);
                    throw new RuntimeException(e);
                }
            });
        }
        return Arc.DEFAULT_ARC;
    }

    public String getInputEprParam() {
        return inputEprParam;
    }

    public void setInputEprParam(String inputEprParam) {
        this.inputEprParam = inputEprParam;
    }

    public StringTemplate getXmlTemplate() {
        return xmlTemplate;
    }

    @Required
    public void setXmlTemplate(StringTemplate xmlTemplate) {
        this.xmlTemplate = xmlTemplate;
    }
}
