package com.izouma.nineth.web;

import com.izouma.nineth.service.CacheService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.CaseUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@RestController
@RequestMapping("/cache")
@AllArgsConstructor
public class CacheController {

    private final CacheService cacheService;

    @RequestMapping("/clear")
    @PreAuthorize("hasRole('ADMIN')")
    public void clear(String name, String stringParam, Long longParam) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Method method;
        if (stringParam != null) {
            method = CacheService.class.getMethod("clear" + StringUtils.capitalize((name)), String.class);
            method.invoke(cacheService, stringParam);
        } else if (longParam != null) {
            method = CacheService.class.getMethod("clear" + StringUtils.capitalize((name)), Long.class);
            method.invoke(cacheService, longParam);
        } else {
            method = CacheService.class.getMethod("clear" + StringUtils.capitalize((name)));
            method.invoke(cacheService);
        }
    }
}
