/**
 * The contents of this file are subject to the license and copyright
 * detailed in the LICENSE and NOTICE files at the root of the source
 * tree and available online at
 *
 * http://www.dspace.org/license/
 */
package org.dspace.importer.external.crossref;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.dspace.importer.external.metadatamapping.contributor.JsonPathMetadataProcessor;

/**
 * This class is used for CrossRef's Live-Import to extract
 * attributes "type" and map it to Depositonce item types.
 * Beans are configured in the crossref-integration.xml file.
 *
 * @author Marwa Saada
 */
public class CrossRefTypeMetadataProcessor implements JsonPathMetadataProcessor {

    private final static Logger log = LogManager.getLogger();

    private String pathToArray;

    private HashMap<String, String> publicationsTypes = new HashMap<String, String>();
    @Override
    public Collection<String> processMetadata(String json) {
        publicationsTypes.put("journal-article", "Article");
        publicationsTypes.put("monograph", "Book");
        publicationsTypes.put("book", "Book");
        publicationsTypes.put("book-chapter", "Book Part");
        publicationsTypes.put("proceedings", "Conference Proceedings");
        publicationsTypes.put("proceedings-article", "Conference Object");
        publicationsTypes.put("report", "Report");
        JsonNode rootNode = convertStringJsonToJsonNode(json);
        JsonNode type = rootNode.at(pathToArray);
        Collection<String> values = new ArrayList<>();
        if (StringUtils.isNoneBlank(type.textValue())) {
            if (publicationsTypes.containsKey(type.textValue())) {
                values.add(publicationsTypes.get(type.textValue()));
            } else {
                values.add(type.textValue());
            }
        }
        return values;
    }

    private JsonNode convertStringJsonToJsonNode(String json) {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode body = null;
        try {
            body = mapper.readTree(json);
        } catch (JsonProcessingException e) {
            log.error("Unable to process json response.", e);
        }
        return body;
    }

    public void setPathToArray(String pathToArray) {
        this.pathToArray = pathToArray;
    }

}
