package eu.dnetlib.uoaadmintools.controllers;

import eu.dnetlib.uoaadmintools.dao.CommunityDAO;
import eu.dnetlib.uoaadmintools.dao.NotificationsDAO;
import eu.dnetlib.uoaadmintools.emailSender.EmailSender;
import eu.dnetlib.uoaadmintools.entities.EmailRecaptcha;
import eu.dnetlib.uoaadmintools.entities.Email;
import eu.dnetlib.uoaadmintools.entities.Notifications;
import eu.dnetlib.uoaadmintools.handlers.ContentNotFoundException;
import eu.dnetlib.uoaadmintools.handlers.InvalidReCaptchaException;
import eu.dnetlib.uoaadmintools.recaptcha.VerifyRecaptcha;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@CrossOrigin(origins = "*")
public class EmailController {
    private final Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private EmailSender emailSender;
    @Autowired
    private NotificationsDAO notificationsDAO;
    @Autowired
    private CommunityDAO communityDAO;
    @Autowired
    private VerifyRecaptcha verifyRecaptcha;

    @RequestMapping(value = "/contact", method = RequestMethod.POST)
    public Boolean contact(@RequestBody EmailRecaptcha form)  throws InvalidReCaptchaException {
        verifyRecaptcha.processResponse(form.getRecaptcha());
        Email email = form.getEmail();
        ArrayList<String> sendTo = new ArrayList<>();
        for(String userMail: email.getRecipients()){
            sendTo.add(userMail);
        }
        return emailSender.send(sendTo, email.getSubject(), email.getBody(), false);
    }

    @RequestMapping(value = "/sendMail", method = RequestMethod.POST)
    public Map<String, ArrayList<String>> sendEmail(@RequestBody Email email,
                                                    @RequestParam(required = false) Optional<Boolean> optional) {
        String successString = "success";
        String failureString = "failure";
        Map<String, ArrayList<String>> mailResults = new HashMap<>();
        boolean bcc = (optional.isPresent())?optional.get():true;
        for(String userMail:email.getRecipients()){
            ArrayList<String> sendTo = new ArrayList<>();
            sendTo.add(userMail);
            boolean success =emailSender.send(sendTo,email.getSubject(),email.getBody(), bcc);
            if(success){
                if(!mailResults.containsKey(successString)) {
                    mailResults.put(successString, new ArrayList<>());
                }
                mailResults.get(successString).add(userMail);
            } else {
                if(!mailResults.containsKey(failureString)) {
                    mailResults.put(failureString, new ArrayList<>());
                }
                mailResults.get(failureString).add(userMail);
            }
        }
        return mailResults;

    }

    @RequestMapping(value = "/notifyForNewManagers/{pid}", method = RequestMethod.POST)
    public Boolean notifyNewManagers(@PathVariable(value = "pid") String pid,@RequestBody Email email ) throws Exception {
        List<String> notifyrecipients = new ArrayList<String>();
        if(communityDAO.findByPid(pid) == null){
            throw new ContentNotFoundException("Community not found");
        }
        for(String user:email.getRecipients()){
            Notifications userNotifications = notificationsDAO.findByManagerEmailAndCommunityPid(user,pid);

            if(userNotifications == null || userNotifications.getNotifyForNewManagers()){
                notifyrecipients.add(user);
            }
        }
        if(notifyrecipients.size() > 0){
            return emailSender.send(notifyrecipients,email.getSubject(),email.getBody(), false);
        }else{
            log.debug("There are no users to notify ");
        }

        return true;
    }
    @RequestMapping(value = "/notifyForNewSubscribers/{pid}", method = RequestMethod.POST)
    public Boolean notifyNewSubscribers(@PathVariable(value = "pid") String pid,@RequestBody Email email ) throws Exception {
        List<String> notifyrecipients = new ArrayList<String>();
        if(communityDAO.findByPid(pid) == null){
            throw new ContentNotFoundException("Community not found");
        }
        for(String user:email.getRecipients()){
            Notifications userNotifications = notificationsDAO.findByManagerEmailAndCommunityPid(user,pid);

            if(userNotifications == null || userNotifications.getNotifyForNewSubscribers()){
                notifyrecipients.add(user);
            }
        }
        if(notifyrecipients.size() > 0){
            return emailSender.send(notifyrecipients,email.getSubject(),email.getBody(), false);
        }else{
            log.debug("There are no users to notify ");
        }

        return true;
    }
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test() throws Exception {
        log.debug("Test mail");
        List<String> mails = new ArrayList<>();
        mails.add("argirok@di.uoa.gr");
        mails.add("argirokokogiannaki@gmail.com");
        log.debug("Recipients"+mails);

        Email email =  new Email();
        email.setRecipients(mails);
        email.setBody("Test body");
        email.setSubject("Test theme");
        String response = "";
        response+=this.notifyNewManagers("ee", email);
        log.debug("Notify managers "+response);

        response+=" ";
        response+=this.notifyNewSubscribers("ee", email);
        log.debug("Notify for subscr "+response);
        return response;

    }

}