package eu.eudat.models.rda.mapper;

import eu.eudat.data.entities.Funder;
import eu.eudat.data.entities.Grant;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.rda.Project;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.transaction.Transactional;
import java.util.*;

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

	@Transactional
	public static Project toRDA(eu.eudat.data.entities.Project project, Grant grant) {
		Project rda = new Project();
		try {
			rda.setTitle(project.getLabel());
			rda.setDescription(project.getDescription());
			if (project.getStartdate() != null) {
				rda.setStart(project.getStartdate().toString());
			}
			if (project.getEnddate() != null) {
				rda.setEnd(project.getEnddate().toString());
			}
			rda.setFunding(Collections.singletonList(FundingRDAMapper.toRDA(grant)));

			if (rda.getTitle() == null) {
				throw new IllegalArgumentException("Project Title is missing");
			}
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage(), e);
		}

		return rda;
	}

	public static Map<String, Object> toEntity(Project rda, ApiContext apiContext) {
		Map<String, Object> entities = new HashMap<>();

		entities.put("project", new eu.eudat.data.entities.Project());
		((eu.eudat.data.entities.Project) entities.get("project")).setLabel(rda.getTitle());
		((eu.eudat.data.entities.Project) entities.get("project")).setDescription(rda.getDescription());
		((eu.eudat.data.entities.Project) entities.get("project")).setId(UUID.randomUUID());
		((eu.eudat.data.entities.Project) entities.get("project")).setStatus((short)1);
		((eu.eudat.data.entities.Project) entities.get("project")).setCreated(new Date());
		((eu.eudat.data.entities.Project) entities.get("project")).setModified(new Date());
		((eu.eudat.data.entities.Project) entities.get("project")).setStartdate(new Date());
		((eu.eudat.data.entities.Project) entities.get("project")).setEnddate(new Date());
		((eu.eudat.data.entities.Project) entities.get("project")).setType(0);
		apiContext.getOperationsContext().getDatabaseRepository().getProjectDao().createOrUpdate(((eu.eudat.data.entities.Project) entities.get("project")));
		for (int i = 0; i < rda.getFunding().size(); i++) {
			entities.put("grant" + (i + 1), FundingRDAMapper.toEntity(rda.getFunding().get(i), apiContext));
		}

		return entities;
	}
}
