package cn.com.qmth.stmms.common.authorization;

import cn.com.qmth.stmms.common.domain.AuthInfo;
import cn.com.qmth.stmms.common.signature.SignatureInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service("authorizationService")
public class AuthorizationService {

    private static final String HEADER_AUTHORIZATION_KEY = "authorization";

    private static final String HEADER_TIME_KEY = "time";

    private static final String HEADER_AUTHINFO_KEY = "auth-info";

    private static final long TIME_AHEAD_SECOND = 5 * 60;

    private static final long TIME_EXPIRE_SECOND = 15 * 60;

    public SignatureInfo buildSignature(long timestamp, String authorization, String method, String uri) {
        if (!expired(timestamp)) {
            return SignatureInfo.parse(method, uri, timestamp, StringUtils.trimToNull(authorization));
        }
        return null;
    }

    public SignatureInfo buildSignature(HttpServletRequest request) {
        long timestamp = 0;
        try {
            timestamp = Long.parseLong(StringUtils.trimToNull(request.getHeader(HEADER_TIME_KEY)));
        } catch (Exception e) {
        }
        if (!expired(timestamp)) {
            return SignatureInfo.parse(request.getMethod(), request.getServletPath(), timestamp,
                    StringUtils.trimToNull(request.getHeader(HEADER_AUTHORIZATION_KEY)));
        }
        return null;
    }

    public SignatureInfo buildSignature(HttpServletRequest request, String time, String authorization) {
        long timestamp = 0;
        try {
            timestamp = Long.parseLong(StringUtils.trimToNull(time));
        } catch (Exception e) {
        }
        if (!expired(timestamp)) {
            return SignatureInfo.parse(request.getMethod(), request.getServletPath(), timestamp,
                    StringUtils.trimToNull(authorization));
        }
        return null;
    }

    public AuthInfo buildAuthInfo(HttpServletRequest request) {
        return AuthInfo.parse(StringUtils.trimToEmpty(request.getHeader(HEADER_AUTHINFO_KEY)));
    }

    private boolean expired(long timestamp) {
        long diff = (System.currentTimeMillis() - timestamp) / 1000;
        return diff < (-1 * TIME_AHEAD_SECOND) || diff > TIME_EXPIRE_SECOND;
    }

}
