package eu.dnetlib.utils.ontologies;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Maps;
import com.google.gson.GsonBuilder;

import eu.dnetlib.data.mapreduce.util.RelDescriptor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Created by sandro on 12/13/16.
 */
public class Ontologies extends HashMap<String, Ontology> {

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

    private Map<String, List<OntologyTerm>> inverse = Maps.newHashMap();

    public String inverseOf(final RelDescriptor rd) {

        if (!containsKey(rd.getRelType())) {
            log.warn(String.format("unable to find ontology '%s'", rd.getRelType()));
            return null;
        }
        return get(rd.getRelType()).inverseOf(rd.getRelClass());
    }

    public List<OntologyTerm> getTerms(final String termCode) {
        if (inverse.isEmpty()) {
            initInverse();
        }
        return inverse.get(termCode);
    }

    private void initInverse() {
        log.info("initialising inverse Ontology terms");
        values().forEach(o -> o.getTerms().values().forEach(t -> {
            if (!inverse.containsKey(t.getCode())) {
                inverse.put(t.getCode(), new ArrayList<>());
            }
            inverse.get(t.getCode()).add(t);
        }));

    }

    public String toJson() {
        return toJson(false);
    }

    public String toJson(boolean pretty) {

        final GsonBuilder gson = new GsonBuilder();
        if (pretty) {
            gson.setPrettyPrinting();
        }

        return gson.create().toJson(this);
    }

    @Override
    public String toString() {
        return toJson();
    }

}
