package it.enea.cruise.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.ws.rs.POST;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import it.enea.cruise.dto.LocalUserDTO;
import it.enea.cruise.model.user.User;
import it.enea.cruise.service.idp.IdpProvider;
import it.enea.cruise.repositories.UserRepository;
import lombok.Getter;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;

@RestController
@Api(value = "UserController")
@Log4j2
@RequiredArgsConstructor
@Getter
@Setter
public class MailController {
	
	@NonNull
	private JavaMailSender emailSender;
	
	@Autowired
    IdpProvider idpClientManager;

	//@Autowired
	//private FreeMarkerConfigurer freemarkerConfigurer;

	@NonNull
    UserRepository userInterface;
	
	//@NonNull
	//IEncryptionManager encryptionManager;

	@Value("${activationLink}")
	private String activationLink;

		
	@POST
	@PostMapping("/user/sendMailMassage")
	public void sendMessageUsingFreemarkerTemplate(LocalUserDTO user)
			throws IOException, TemplateException, MessagingException {

		Map<String, Object> templateModel1 = new HashMap<String, Object>();
		//String subject = encryptionManager.encrypt(user.getEmail());
		String subject = user.getSubject();
		templateModel1.put("link", activationLink + subject);
		templateModel1.put("recipientName", user.getName() + " " + user.getSurname());
		try {
			String htmlBody = FreeMarkerUtils.getHtml("mailMassage_it_IT.ftl", templateModel1);
			sendHtmlMessage(user.getEmail(), "Activate your registration to SmartEnergyCommunity", htmlBody);
		}catch (Exception e) {
			log.error("Error message:" + e.getLocalizedMessage(), e);
		}

	}
	
	@POST
	@PostMapping("/user/sendEmptyMailMassage")
	public void sendEmptyMessage(
			@RequestHeader(name = "Authorization", required=true) String token,
			String destination)
			throws IOException, TemplateException, MessagingException {
		if (idpClientManager.isValid(token)) {
			Map<String, Object> templateModel1 = new HashMap<String, Object>();
		

		templateModel1.put("link", activationLink);
		templateModel1.put("recipientName", "Test Test");
		try {
			String htmlBody = FreeMarkerUtils.getHtml("mailMassage_it_IT.ftl", templateModel1);
			sendHtmlMessage(destination, "Activate your registration to SmartEnergyCommunity", htmlBody);
		}catch (Exception e) {
			log.error("Error message:" + e.getLocalizedMessage(), e);
		}
		}
	}

	private void sendHtmlMessage(String to, String subject, String htmlBody) throws MessagingException {
		MimeMessage message = emailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
		helper.setTo(to);
		helper.setSubject(subject);
		helper.setText(htmlBody, true);
		helper.setFrom("utt.noreply@enea.it");
		emailSender.send(message);
	}

	/*
	 * Acrivate user 
	 */
	
	
	@POST
	@PostMapping("/user/activate")
	public Boolean activateUser(
			@RequestBody ActivateRequest request) throws IOException, TemplateException, MessagingException {
		log.info ("Subject: " + request.getSubject());
		String subject = request.getSubject();
			User user = userInterface.findUserBySubject(subject);
			user.setActive(true);
			userInterface.save(user);
		if (user.getActive() == true) {
			return true;
		} else
			return false;
	}

	@Getter
	@Setter
	public static class ActivateRequest {
	    protected String subject;
	    protected String lang;
	}

	
}
