package com.bcxin.wps.util;

import cn.wps.solution.weboffice.provider.v3.exception.InvalidArgument;
import cn.wps.solution.weboffice.provider.v3.exception.InvalidToken;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

public class WpsRequestUtils {
    private WpsRequestUtils() {
    }

    public static HttpServletRequest getCurrentRequest() {
        // #ServletUriComponentsBuilder.getCurrentRequest()
        RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
        Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");
        return ((ServletRequestAttributes) attrs).getRequest();

    }

    public static String getWebOfficeToken(HttpServletRequest request) {
        final String token;
        if (Objects.isNull((token = request.getHeader("X-Weboffice-Token")))) {
            throw new InvalidToken("weboffice token is required");
        }
        return token;
    }

    public static String getAppId(HttpServletRequest request) {
        final String appId;
        if (Objects.isNull((appId = request.getHeader("X-App-Id")))) {
            throw new InvalidArgument("app id is required");
        }
        return appId;
    }

    public static String getRequestId(HttpServletRequest request) {
        final String requestId;
        if (Objects.isNull(requestId = request.getHeader("X-Request-Id"))) {
            return "";
        }
        return requestId;
    }

}
