package eu.dnetlib.uoaadmintools.controllers;

import eu.dnetlib.uoaadmintools.configuration.properties.BrowserCacheConfig;
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 org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/cache")
@CrossOrigin(origins = "*")
public class BrowserCacheController {
    private final Logger log = Logger.getLogger(this.getClass());

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private BrowserCacheConfig config;

    @PreAuthorize("hasAnyAuthority(" +
            "@AuthorizationService.PORTAL_ADMIN, " +
            "@AuthorizationService.curator('community'), @AuthorizationService.manager('community', #pid))")
    @RequestMapping(value = "/{pid}", method = RequestMethod.GET)
    public boolean purge(@PathVariable(value = "pid") String pid) {
//        try {
            restTemplate.getForEntity(config.getUrl().replace("{community}", pid), String.class);
//        } catch(HttpClientErrorException httpClientErrorException) {
//            log.debug("Purge browser cache: HttpClientErrorException for "+pid + " - code: " + httpClientErrorException.getStatusCode());
//            return false;
//        } catch(ResourceAccessException resourceAccessException) {
//            log.debug("Purge browser cache: ResourceAccessException for "+pid);
//            return false;
//        } catch(Exception exception) {
//            log.debug("Purge browser cache: " + exception.getClass() + " for "+pid);
//            return false;
//        }
        return true;
    }
}
