package eu.eudat.models.rda.mapper;

import eu.eudat.data.dao.criteria.GrantCriteria;
import eu.eudat.data.entities.Funder;
import eu.eudat.data.entities.Grant;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.rda.Funding;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.UUID;

public class FundingRDAMapper {

	@Transactional
	public static Funding toRDA(Grant grant) {
		Funding rda = new Funding();
		String referencePrefix;
		String shortReference;
		if (grant.getFunder().getReference() != null) {
			referencePrefix = grant.getFunder().getReference().split(":")[0];
			shortReference = grant.getFunder().getReference().substring(referencePrefix.length() + 1);
			rda.setFunderId(FunderIdRDAMapper.toRDA(shortReference));
		} else {
			rda.setFunderId(FunderIdRDAMapper.toRDA(grant.getFunder().getId()));
		}
		if (grant.getReference() != null) {
			referencePrefix = grant.getReference().split(":")[0];
			shortReference = grant.getReference().substring(referencePrefix.length() + 1);
			rda.setGrantId(GrantIdRDAMapper.toRDA(shortReference));
		} else {
			rda.setGrantId(GrantIdRDAMapper.toRDA(grant.getId().toString()));
		}
		return rda;
	}

	public static Grant toEntity(Funding rda, ApiContext apiContext) {
		GrantCriteria criteria = new GrantCriteria();
		criteria.setReference(rda.getGrantId().getIdentifier());
		Grant grant;
		try {
			 grant = apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().getWithCriteria(criteria).getSingle();
		}catch (Exception e) {
			grant = new Grant();
			grant.setId(UUID.randomUUID());
			grant.setLabel(rda.getGrantId().getIdentifier());
			grant.setStatus((short)1);
			grant.setCreated(new Date());
			grant.setModified(new Date());
			grant.setType(0);
			grant.setFunder(new Funder());
			grant.getFunder().setId(UUID.randomUUID());
			grant.getFunder().setLabel(rda.getFunderId().getIdentifier());
			grant.getFunder().setStatus((short)1);
			grant.getFunder().setCreated(new Date());
			grant.getFunder().setModified(new Date());
			grant.getFunder().setType(0);
			grant.getFunder().setReference(rda.getFunderId().getType().toString()+"::"+rda.getFunderId().getIdentifier());
			grant.setReference(rda.getGrantId().getType().toString()+"::"+rda.getGrantId().getIdentifier());
			Funder funder = apiContext.getOperationsContext().getDatabaseRepository().getFunderDao().createOrUpdate(grant.getFunder());
			grant = apiContext.getOperationsContext().getDatabaseRepository().getGrantDao().createOrUpdate(grant);
		}
		return grant;
	}
}
