package eu.eudat.logic.managers;

import eu.eudat.data.entities.UserInfo;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.ContactEmail.ContactEmailModel;
import eu.eudat.models.data.ContactEmail.PublicContactEmailModel;
import eu.eudat.models.data.mail.SimpleMail;
import eu.eudat.models.data.security.Principal;
import org.springframework.core.env.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;

@Component
public class ContactEmailManager {

	private ApiContext apiContext;
	private Environment environment;

	@Autowired
	public ContactEmailManager(ApiContext apiContext, Environment environment) {
		this.apiContext = apiContext;
		this.environment = environment;
	}

	public void sendContactEmail(ContactEmailModel contactEmailModel, Principal principal) throws MessagingException {
		UserInfo user = apiContext.getOperationsContext().getDatabaseRepository().getUserInfoDao().find(principal.getId());
		SimpleMail mail = new SimpleMail();
		String enrichedMail = contactEmailModel.getDescription() + "\n\n" + "Send by user: " + user.getEmail() ;
		mail.setSubject(contactEmailModel.getSubject());
		mail.setTo(environment.getProperty("contact_email.mail"));
		mail.setContent(enrichedMail);
		mail.setFrom(user.getEmail());

		apiContext.getUtilitiesService().getMailService().sendSimpleMail(mail);
	}

	public void sendContactEmailNoAuth(PublicContactEmailModel contactEmailModel) throws MessagingException {
		SimpleMail mail = new SimpleMail();
		String enrichedMail = contactEmailModel.getMessage() + "\n\n" + "Send by user: " + contactEmailModel.getEmail() ;
		mail.setSubject(contactEmailModel.getAffiliation());
		mail.setTo(environment.getProperty("contact_email.mail"));
		mail.setContent(enrichedMail);
		mail.setFrom(contactEmailModel.getEmail());

		apiContext.getUtilitiesService().getMailService().sendSimpleMail(mail);
	}

	public void emailValidation(ContactEmailModel contactEmailModel) throws Exception {
		if (contactEmailModel.getSubject() == null || contactEmailModel.getSubject().trim().isEmpty()) {
			throw new Exception("Subject is empty");
		}
		if (contactEmailModel.getDescription() == null || contactEmailModel.getDescription().trim().isEmpty()) {
			throw new Exception("Description is empty");
		}
	}
}
