package cn.reghao.autodop.dmaster.spring.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截 webhook 发出的 POST 请求
 *
 * @author reghao
 * @date 2020-09-08 17:16:37
 */
@Slf4j
@Component
public class WebhookInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String source = request.getParameter("source");
        switch (WebhookSource.valueOf(source)) {
            case codeup:
                String event = request.getHeader("X-Codeup-Event");
                String deliveryId = request.getHeader("x-codeup-delivery");
                if (event == null || deliveryId == null) {
                    return false;
                }
                break;
            case gogs:
                break;
            case git:
                break;
            case svn:
                break;
            default:
                return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           @Nullable ModelAndView modelAndView) throws Exception {
        log.info("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler, @Nullable Exception ex) throws Exception {
        log.info("afterCompletion");
    }

    enum WebhookSource {
        codeup("Codeup"), gogs("Gogs"), git("Git"), svn("SVN");

        private String value;

        WebhookSource(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }
}
