package eu.eudat.logic.managers;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import eu.eudat.data.entities.DMP;
import eu.eudat.models.rda.Dmp;
import eu.eudat.models.rda.RDAModel;
import eu.eudat.models.rda.mapper.DmpRDAMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;
import java.io.IOException;
import java.text.SimpleDateFormat;

@Component
public class RDAManager {

	private DmpRDAMapper dmpRDAMapper;

	@Autowired
	public RDAManager(DmpRDAMapper dmpRDAMapper) {
		this.dmpRDAMapper = dmpRDAMapper;
	}

	@Transactional
	public String convertToRDA(DMP dmp) throws JsonProcessingException {
		String result = "";

		Dmp rdaDmp = dmpRDAMapper.toRDA(dmp);

		ObjectMapper mapper = new ObjectMapper();
		mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"));

		RDAModel model = new RDAModel();
		model.setDmp(rdaDmp);
		result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(model);

		return result;
	}

	public DMP convertToEntity(String json, String[] profiles) throws IOException {
		ObjectMapper mapper = new ObjectMapper();

		Dmp rda = mapper.readValue(json, RDAModel.class).getDmp();
		return dmpRDAMapper.toEntity(rda, profiles);
	}
}
