package eu.eudat.models.rda.mapper;

import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.data.entities.Researcher;
import eu.eudat.data.entities.UserDMP;
import eu.eudat.models.rda.Contributor;
import eu.eudat.models.rda.ContributorId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;

public class ContributorRDAMapper {
	private static final Logger logger = LoggerFactory.getLogger(ContributorRDAMapper.class);

	public static Contributor toRDA(UserDMP userDMP) {
		Contributor rda = new Contributor();
		rda.setContributorId(ContributorIdRDAMapper.toRDA(userDMP.getUser().getId()));
		if (userDMP.getUser().getName() == null) {
			throw new IllegalArgumentException("Contributor Name is missing");
		}
		rda.setName(userDMP.getUser().getName());
		rda.setMbox(userDMP.getUser().getEmail());
		rda.setRole(new HashSet<>(Arrays.asList(UserDMP.UserDMPRoles.fromInteger(userDMP.getRole()).name())));
		return rda;
	}

	public static Contributor toRDA(Researcher researcher) {
		Contributor rda = new Contributor();
		rda.setContributorId(ContributorIdRDAMapper.toRDA(researcher.getReference()));
		rda.setName(researcher.getLabel());
		rda.setMbox(researcher.getPrimaryEmail());
//		rda.setRole(new HashSet<>(Arrays.asList(UserDMP.UserDMPRoles.fromInteger(userDMP.getRole()).name())));
		return rda;
	}

	public static Contributor toRDA(String value) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			eu.eudat.models.data.dmp.Researcher researcher = mapper.readValue(value, eu.eudat.models.data.dmp.Researcher.class);
			return toRDA(researcher.toDataModel());
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	public static Researcher toEntity(Contributor rda) {
		Researcher entity = new Researcher();
		String reference;
		if (rda.getContributorId() != null) {
			if (rda.getContributorId().getType() == ContributorId.Type.ORCID) {
				String id = rda.getContributorId().getIdentifier().replace("http://orcid.org/", "");
				reference = "orcid:" + id;
			} else {
				String idParts[] = rda.getContributorId().getIdentifier().split(":");
				if (idParts.length == 1) {
					reference = "dmp:" + rda.getContributorId().getIdentifier();
				} else {
					reference = rda.getContributorId().getIdentifier();
				}
			}
			entity.setReference(reference);
			entity.setLabel(rda.getName());
			entity.setPrimaryEmail(rda.getMbox());
		} else {
			return null;
		}

		return entity;
	}
}
