package eu.dnetlib.data.dedup;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.google.common.collect.Maps;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpService;
import eu.dnetlib.functionality.index.solr.feed.InputDocumentFactory;
import eu.dnetlib.functionality.modular.ui.dedup.SimilarityGroup;
import eu.dnetlib.miscutils.datetime.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class DedupUserActionsDAOImpl extends AbstractDedupDAO implements DedupUserActionsDAO {

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

	@Autowired
	private DedupDbDAO dbDAO;

	@Autowired
	private DedupIndexDAO indexDAO;

	@Override
	public Map<String, List<String>> listConfigurations() throws ISLookUpException {
		final Map<String, List<String>> res = Maps.newHashMap();

		final ISLookUpService lookUpService = serviceLocator.getService(ISLookUpService.class);
		final String listEntityTypesXQuery =
				"distinct-values(for $x in //RESOURCE_PROFILE["
						+ ".//RESOURCE_TYPE/@value = 'DedupOrchestrationDSResourceType' and "
						+ ".//CONFIGURATION/@enabled='true'] return $x//ENTITY/@name/string())";

		for (final String entityType : lookUpService.quickSearchProfile(listEntityTypesXQuery)) {
			final String xquery =
					String.format(
							"for $x in //RESOURCE_PROFILE[" +
									".//RESOURCE_TYPE/@value = 'DedupOrchestrationDSResourceType' and .//ENTITY/@name='%s' ] " +
									"return $x//ACTION_SET/@id/string()", entityType);
			res.put(entityType, lookUpService.quickSearchProfile(xquery));
		}

		if (log.isDebugEnabled()) {
			log.debug("found configurations: " + res);
		}
		return res;
	}

	@Override
	public OafResult search(final String type, final String userQuery, final String actionSet, final int start, final int rows, final String fields)
			throws Exception {

		return indexDAO.search(type, userQuery, actionSet, start, rows, fields);
	}

	@Override
	public OafResult searchById(final String actionSet, final String type, final String objidentifier, final List<String> fields) throws Exception {

		return indexDAO.searchById(actionSet, type, objidentifier, fields);
	}

	@Override
	public boolean commit(final SimilarityGroup group) throws Exception {
		if (StringUtils.isBlank(group.getActionSet())) throw new IllegalArgumentException("missing actionset");

		group.setId(UUID.randomUUID().toString());
		group.setDate(InputDocumentFactory.getParsedDateField(DateUtils.now_ISO8601()));

		return dbDAO.commit(group) && indexDAO.commit(group);
	}

}
