package eu.dnetlib.uoaadmintools.controllers;

import eu.dnetlib.uoaadmintools.dao.NotificationsDAO;
import eu.dnetlib.uoaadmintools.entities.Manager;
import eu.dnetlib.uoaadmintools.entities.Notifications;
import eu.dnetlib.uoaadmintools.services.ManagerService;
import eu.dnetlib.uoaadmintoolslibrary.dao.PortalDAO;
import eu.dnetlib.uoaadmintoolslibrary.emailSender.EmailSender;
import eu.dnetlib.uoaadmintoolslibrary.entities.email.Email;
import eu.dnetlib.uoaadmintoolslibrary.entities.email.EmailRecaptcha;
import eu.dnetlib.uoaadmintoolslibrary.handlers.ContentNotFoundException;
import eu.dnetlib.uoaadmintoolslibrary.handlers.InvalidReCaptchaException;
import eu.dnetlib.uoaadmintoolslibrary.handlers.utils.RolesUtils;
import eu.dnetlib.uoaadmintoolslibrary.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 PortalDAO portalDAO;
    @Autowired
    private VerifyRecaptcha verifyRecaptcha;
    @Autowired
    private ManagerService managerService;
    @Autowired
    private RolesUtils rolesUtils;

    @RequestMapping(value = "/contact", method = RequestMethod.POST)
    public Boolean contact(@RequestBody EmailRecaptcha form)  throws InvalidReCaptchaException {
        if(form.getRecaptcha() != null) {
            verifyRecaptcha.processResponse(form.getRecaptcha());
        }
        Email email = form.getEmail();
        ArrayList<String> sendTo = new ArrayList<>(email.getRecipients());
        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 = "/notifyNewManager", method = RequestMethod.POST)
    public Boolean notifyNewManager(@RequestBody Email email) throws Exception {
        String userMail = rolesUtils.getEmail();
        ArrayList<String> sendTo = new ArrayList<>();
        sendTo.add(userMail);
        boolean success =emailSender.send(sendTo,email.getSubject(),email.getBody(), true);

        return success;
    }

    @RequestMapping(value = "/notifyManagers/{pid}/{newRoleType}", method = RequestMethod.POST)
    public Boolean notifyManagers(@PathVariable(value = "pid") String pid,
                                  @PathVariable(value = "newRoleType") String newRoleType,
                                  @RequestBody Email email ) throws Exception {
        List<String> notifyrecipients = new ArrayList<String>();
        if(portalDAO.findByPid(pid) == null){
            throw new ContentNotFoundException("Portal not found");
        }

        Manager[] managers = managerService.getManagers(pid);
        List<String> emails = new ArrayList();

        for(Manager manager:managers){
            String userEmail = manager.getEmail();
            emails.add(userEmail);

            // Do not send the notification to the new manager/ subscriber.
            if(userEmail.equals(rolesUtils.getEmail())) {
                continue;
            }

            Notifications userNotifications = notificationsDAO.findByManagerEmailAndPortalPid(userEmail,pid);

            if(userNotifications == null
                    || (newRoleType.equals("manager") && userNotifications.getNotifyForNewManagers())
                    || (newRoleType.equals("subscriber") && userNotifications.getNotifyForNewSubscribers())){
                notifyrecipients.add(userEmail);
            }
        }
        if(notifyrecipients.size() > 0){
            email.setBody(email.getBody().replace("((__managers__))", String.join(", ", emails)));

            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(portalDAO.findByPid(pid) == null){
//            throw new ContentNotFoundException("Portal not found");
//        }
//        for(String user:email.getRecipients()){
//            Notifications userNotifications = notificationsDAO.findByManagerEmailAndPortalPid(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.notifyManagers("ee", "manager", email);
        log.debug("Notify managers "+response);

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

    }

}