package com.inspect.ivs.config;

import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Order(5)
@Component
public class SysLogAop {
    private static final Logger log = LoggerFactory.getLogger(SysLogAop.class);

    @Pointcut("execution(public * com.inspect.ivs.controller.*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            log.debug("<++++++++++++++++++++++++++++++++++++++++REQUEST++++++++++++++++++++++++++++++++++++++++++>");
            log.debug("[IVS] URL: {}", request.getRequestURL().toString());
            log.debug("[IVS] HTTP_METHOD: {}", request.getMethod());
            log.debug("[IVS] CLASS_METHOD: {}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
            log.debug("[IVS] ARGS: {}", Arrays.toString(joinPoint.getArgs()));
        }
    }

    @AfterReturning(
            returning = "ret",
            pointcut = "webLog()"
    )
    public void doAfterR(Object ret) throws Throwable {
        String s = ret.toString();
        log.debug("[IVS] RESPONSE: {}", (s.length() > 100 ? s.substring(0, 100) : s));
        log.debug("<++++++++++++++++++++++++++++++++++++++++RESPONSE++++++++++++++++++++++++++++++++++++++++++>");
    }
}
