package eu.dnetlib.uoaadmintools.controllers;

import eu.dnetlib.uoaadmintools.dao.NotificationsDAO;
import eu.dnetlib.uoaadmintools.entities.Notifications;
import eu.dnetlib.uoaadmintoolslibrary.dao.PortalDAO;
import eu.dnetlib.uoaadmintoolslibrary.entities.Portal;
import eu.dnetlib.uoaadmintoolslibrary.handlers.ContentNotFoundException;
import eu.dnetlib.uoaadmintoolslibrary.handlers.MismatchingContentException;
import eu.dnetlib.uoaadmintoolslibrary.handlers.utils.RolesUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by argirok on 6/7/2018.
 */
@RestController
@CrossOrigin(origins = "*")
public class NotificationsController {
    private final Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private NotificationsDAO notificationsDAO;
    @Autowired
    private PortalDAO portalDAO;
    @Autowired
    private RolesUtils rolesUtils;

    @PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
    @RequestMapping(value = "/community/{pid}/notifications/all", method = RequestMethod.GET)
    public List<Notifications> getNotifications(@PathVariable(value = "pid") String pid ) throws ContentNotFoundException {
        Portal portal = portalDAO.findByPid(pid);
        if(portal == null){
            throw new ContentNotFoundException("Portal with pid: "+pid+" not found");
        }
        if(!portal.getType().equals("community")) {
            // EXCEPTION - MismatchingContent
            throw new MismatchingContentException("Get Notifications: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of community");
        }

        List<Notifications> notifications = notificationsDAO.findByPortalPid(pid);
        if(notifications == null || notifications.size() == 0){
            throw new ContentNotFoundException("Notifications settings for community with pid: "+pid+" not found");
        }
        return notifications;
    }

    @PreAuthorize("hasAnyAuthority(" +
            "@AuthorizationService.PORTAL_ADMIN, " +
            "@AuthorizationService.curator('community'), @AuthorizationService.manager('community', #pid))")
    @RequestMapping(value = "/community/{pid}/notifications", method = RequestMethod.GET)
    public Notifications getNotificationsForUser(@PathVariable(value = "pid") String pid) throws ContentNotFoundException {
        Portal portal = portalDAO.findByPid(pid);
        if(portal == null){
            throw new ContentNotFoundException("Portal with pid: "+pid+" not found");
        }
        if(!portal.getType().equals("community")) {
            // EXCEPTION - MismatchingContent
            throw new MismatchingContentException("Get Notifications: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of community");
        }

        String email = rolesUtils.getEmail();

        Notifications notifications = notificationsDAO.findByManagerEmailAndPortalPid(email, pid);
        if(notifications == null){
            throw new ContentNotFoundException("Notifications settings for community with pid: "+pid+" and user email: "+email+" not found");
        }
        return notifications;
    }

    @PreAuthorize("hasAnyAuthority(" +
            "@AuthorizationService.PORTAL_ADMIN, " +
            "@AuthorizationService.curator('community'), @AuthorizationService.manager('community', #pid))")
    @RequestMapping(value = "/community/{pid}/notifications", method = RequestMethod.DELETE)
    public void deleteNotification(@PathVariable(value = "pid") String pid) throws ContentNotFoundException {
        Portal portal = portalDAO.findByPid(pid);
        if(portal == null){
            throw new ContentNotFoundException("Portal with pid: "+pid+" not found");
        }
        if(!portal.getType().equals("community")) {
            // EXCEPTION - MismatchingContent
            throw new MismatchingContentException("Delete Notifications: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of community");
        }
        String email = rolesUtils.getEmail();
        Notifications notifications = notificationsDAO.findByManagerEmailAndPortalPid(email,pid);
        if(notifications!= null){
            notificationsDAO.delete(notifications.getId());
        }else{
            throw new ContentNotFoundException("Notifications settings for community with pid: "+pid+" and user email: "+email+" not found");
        }

    }

    @PreAuthorize("hasAnyAuthority(" +
            "@AuthorizationService.PORTAL_ADMIN, " +
            "@AuthorizationService.curator('community'), @AuthorizationService.manager('community', #pid))")
    @RequestMapping(value = "/community/{pid}/notifications", method = RequestMethod.POST)
    public Notifications saveNotification(@PathVariable(value = "pid") String pid, @RequestBody Notifications notifications) throws ContentNotFoundException {
        Portal portal = portalDAO.findByPid(pid);
        if(portal == null){
            throw new ContentNotFoundException("Portal with pid: "+pid+" not found");
        }
        if(!portal.getType().equals("community")) {
            // EXCEPTION - MismatchingContent
            throw new MismatchingContentException("Save Notifications: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of community");
        }

        notifications.setManagerEmail(rolesUtils.getEmail());
        notifications.setAaiId(rolesUtils.getAaiId());

//        if(notifications.getManagerEmail() != null && !notifications.getManagerEmail().isEmpty()){
            Notifications saved = notificationsDAO.findByManagerEmailAndPortalPid(notifications.getManagerEmail(),pid);
            log.debug(saved);
            if(saved!= null){
                notifications.setId(saved.getId());
            }

            notifications.setPortalPid(pid);
            log.debug(notifications);
            Notifications savedNotifications = notificationsDAO.save(notifications);
            return savedNotifications;
//        } else{
//            log.error("Save notifications: No user e-mail specified");
//            return null;
//        }


    }

}
