package eu.dnetlib.uoaadmintools.controllers;

import eu.dnetlib.uoaadmintoolslibrary.entities.Portal;
import eu.dnetlib.uoaadmintoolslibrary.entities.fullEntities.PortalResponse;
import eu.dnetlib.uoaadmintoolslibrary.handlers.ContentNotFoundException;
import eu.dnetlib.uoaadmintoolslibrary.handlers.MismatchingContentException;
import eu.dnetlib.uoaadmintoolslibrary.services.PortalService;
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;

@RestController
@RequestMapping("/explore")
@CrossOrigin(origins = "*")
@PreAuthorize("hasAnyAuthority(@AuthorizationService.PORTAL_ADMIN)")
public class ExploreController {
    private final Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private PortalService portalService;

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public PortalResponse updateExplore(@RequestBody Portal portal) {
        if(!portal.getType().equals("explore")) {
            // EXCEPTION - MismatchingContent
            throw new MismatchingContentException("Update Explore: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of explore");
        }
        PortalResponse portalResponse = portalService.updatePortal(portal);
        return portalResponse;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public PortalResponse insertExplore(@RequestBody Portal portal) {
        if(!portal.getType().equals("explore")) {
            // EXCEPTION - MismatchingContent
            throw new MismatchingContentException("Save Explore: Portal with id: "+portal.getId()+" has type: "+portal.getType()+" instead of explore");
        }
        PortalResponse portalResponse = portalService.insertPortal(portal);
        return portalResponse;
    }

    // cannot handle MismatchingContent
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Boolean deleteExplore(@RequestBody List<String> portals) throws Exception {
        for (String id : portals) {
            Portal portal = portalService.getPortalById(id);
            if(portal == null) {
                // EXCEPTION - Entity Not Found
                throw new ContentNotFoundException("Delete Explore: Portal with id: " + id + " not found");
            }
            if(!portal.getType().equals("explore")) {
                // EXCEPTION - MismatchingContent
                throw new MismatchingContentException("Delete Explore: Portal with id: "+id+" has type: "+portal.getType()+" instead of explore");
            }
            portalService.deletePortal(id);
        }

        return true;
    }
}

