package eu.dnetlib.server.widget;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import eu.dnetlib.client.widgets.AutoCompleteService;
import eu.dnetlib.goldoa.domain.Vocabulary;
import eu.dnetlib.goldoa.service.SearchManager;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by stefania on 3/2/15.
 */
public class AutoCompleteServiceImpl extends RemoteServiceServlet implements AutoCompleteService {

    private SearchManager searchManager = null;

    public void init(ServletConfig config) throws ServletException {

        super.init(config);

        ApplicationContext context = WebApplicationContextUtils
                .getWebApplicationContext(getServletContext());

        this.searchManager = (SearchManager) context.getBean("searchManager");
    }

    @Override
    public List<Vocabulary> getAutoCompleteVocabulary(String type, String matchString) {

        List<Vocabulary> matchingNames = new ArrayList<Vocabulary>();

        try {
            SearchManager.TYPE searchType = SearchManager.TYPE.ORGANISATION;
            if (type.equals("project"))
                searchType = SearchManager.TYPE.PROJECT;
            else if (type.equals("organisation"))
                searchType = SearchManager.TYPE.ORGANISATION;
            else if (type.equals("journal"))
                searchType = SearchManager.TYPE.JOURNAL;
            else if (type.equals("publisher"))
                searchType = SearchManager.TYPE.PUBLISHER;
            else if (type.equals("funder"))
                searchType = SearchManager.TYPE.FUNDER;

            List<Vocabulary> vocabularyList = searchManager.search(searchType, matchString);


            for (Vocabulary vocabulary : vocabularyList) {
                matchingNames.add(new Vocabulary(vocabulary.getId(), vocabulary.getName()));
            }
        } catch(Exception e) {
            e.printStackTrace();
        }

        return matchingNames;
    }
}
