package eu.dnetlib.uoaadmintools.controllers;

import eu.dnetlib.uoaadmintools.dao.CommunityDAO;
import eu.dnetlib.uoaadmintools.dao.NotificationsDAO;
import eu.dnetlib.uoaadmintools.entities.Notifications;
import eu.dnetlib.uoaadmintools.handlers.ContentNotFoundException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
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 CommunityDAO communityDAO;

    @RequestMapping(value = "/community/{pid}/notifications", method = RequestMethod.GET)
    public List<Notifications> getNotifications(@PathVariable(value = "pid") String pid ) throws ContentNotFoundException {
        if(communityDAO.findByPid(pid) == null){
            throw new ContentNotFoundException("Community not found");
        }
        List<Notifications> notifications = notificationsDAO.findByCommunityPid(pid);
        if(notifications == null || notifications.size() == 0){
            throw new ContentNotFoundException("Notifications settings not found");
        }
        return notifications;
    }
    @RequestMapping(value = "/community/{pid}/notifications", method = RequestMethod.DELETE)
    public void deleteEntity(@PathVariable(value = "pid") String pid, @RequestBody String email) throws ContentNotFoundException {
        Notifications notifications = notificationsDAO.findByManagerEmailAndCommunityPid(email,pid);
        if(notifications!= null){
            notificationsDAO.delete(notifications.getId());
        }else{
            throw new ContentNotFoundException("Notifications not found");
        }

    }

    @RequestMapping(value = "/community/{pid}/notifications", method = RequestMethod.POST)
    public Notifications saveEntity(@PathVariable(value = "pid") String pid, @RequestBody Notifications notifications) throws ContentNotFoundException {
        if(communityDAO.findByPid(pid) == null){
            throw new ContentNotFoundException("Community not found");
        }

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

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


    }

}
