package eu.dnetlib.uoaadmintools.services;

import eu.dnetlib.uoaadmintools.dao.PortalSubscribersDAO;
import eu.dnetlib.uoaadmintools.entities.subscriber.PortalSubscribers;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SubscriberService {
    private final Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private PortalSubscribersDAO portalSubscribersDAO;

    public void updatePid(String old_pid, String new_pid) {
        log.debug("subscriber service: updatePid");
        PortalSubscribers portalSubscribers =  portalSubscribersDAO.findByPid(old_pid);
        log.debug("subscriber service: portalSubscribers id: "+(portalSubscribers != null ? portalSubscribers.getId() : "not found"));
        if(portalSubscribers != null) {
            portalSubscribers.setPid(new_pid);
            log.debug("subscriber portalSubscribers: new portalSubscribers pid: " + portalSubscribers.getPid());
            portalSubscribersDAO.save(portalSubscribers);
            log.debug("portalSubscribers saved!");
        }
    }

    public void createPortalSubscribers(String pid) {
        PortalSubscribers portalSubscribers =  new PortalSubscribers(pid);
        portalSubscribersDAO.save(portalSubscribers);
    }

    public void deletePortalSubscribers(String pid) {
        PortalSubscribers portalSubscribers = portalSubscribersDAO.findByPid(pid);
        if(portalSubscribers != null) {
            portalSubscribersDAO.delete(portalSubscribers.getId());
        }
    }
}
