package com.wecloud.im.sdk.internal;

import com.wecloud.im.sdk.ClientException;
import com.wecloud.im.sdk.common.RequestMessage;
import com.wecloud.im.sdk.common.auth.Credentials;

/**
 * 请求签名者
 * @Author luozh
 * @Date 2022年04月14日 11:25
 * @Version 1.0
 */
public class RequestSigner {

    private String httpMethod;

    /* Note that resource path should not have been url-encoded. */
    private String resourcePath;

    private Credentials creds;

    public RequestSigner(String httpMethod, String resourcePath, Credentials creds) {
        this.httpMethod = httpMethod;
        this.resourcePath = resourcePath;
        this.creds = creds;
    }

    public void sign(RequestMessage request) throws ClientException {
        String accessKeyId = creds.getAppKey();
        String secretAccessKey = creds.getAppSecret();

        if (accessKeyId.length() > 0 && secretAccessKey.length() > 0) {
            String signature;
            signature = SignUtils.buildSignature(secretAccessKey, httpMethod, resourcePath, request);
            request.addHeader(ImHeaders.AUTHORIZATION, SignUtils.composeRequestAuthorization(accessKeyId, signature));
        }
    }
}
