package com.wecloud.im.sdk.internal;

import okhttp3.Response;

import java.net.URL;
import java.util.Date;

import cn.hutool.core.date.DateUtil;

import com.wecloud.im.sdk.common.HttpClient;
import com.wecloud.im.sdk.common.HttpMethod;
import com.wecloud.im.sdk.common.RequestMessage;
import com.wecloud.im.sdk.common.auth.Credentials;
import com.wecloud.im.sdk.exception.WecloudException;

import static com.wecloud.im.sdk.internal.ImHeaders.X_IM_FROM;
import static com.wecloud.im.sdk.utils.HttpHeaders.CONTENT_TYPE;

/**
 *
 * @Author luozh
 * @Date 2022年04月13日 13:47
 * @Version 1.0
 */
public abstract class WecloudImOperation {

    protected URL apiDomain;

    protected String appKey;

    protected String appSecret;

    public WecloudImOperation(URL apiDomain, String appKey, String appSecret) {
        this.apiDomain = apiDomain;
        this.appKey = appKey;
        this.appSecret = appSecret;
    }

    protected Object doOperation(RequestMessage request) {
        Credentials credentials = new Credentials(appKey, appSecret);
        // 请求日期
        String date = DateUtil.formatHttpDate(new Date());
        request.addHeader(ImHeaders.DATE, date);
        if (HttpMethod.POST.equals(request.getMethod())) {
            request.addHeader(CONTENT_TYPE, "application/json; charset=utf-8");
        }
        // 添加来源请求头
        request.addHeader(X_IM_FROM, "server");
        // 添加签名请求头
        RequestSigner signer = new RequestSigner(request.getMethod().name(), request.getEndpoint(), credentials);
        signer.sign(request);
        return send(request);
    }

    @SuppressWarnings("unchecked")
    private Object send(RequestMessage request) {
        try {
            // 组装请求
            URL endpoint = new URL(apiDomain, request.getEndpoint());
            HttpClient httpClient =
                    HttpClient.builder().url(endpoint).addHeaders(request.getHeaders()).addParams(request.getParameters());

            if (HttpMethod.POST.equals(request.getMethod())) {
                httpClient.post(true);
            } else {
                httpClient.get();
            }
            Response response = httpClient.sync();

            if (!Integer.valueOf(200).equals(response.code())) {
                throw new RuntimeException("请求报错: " + response.code());
            }

            assert response.body() != null;
            String responseBody = response.body().string();
            return ResponseParser.parse(responseBody);

        } catch (Exception e) {
            throw new WecloudException("发送请求报错: " + e.getMessage());
        }
    }

    private static RequestSigner createSigner(HttpMethod method, String bucketName, String key, Credentials creds) {
        String resourcePath = "/" + ((bucketName != null) ? bucketName + "/" : "") + ((key != null ? key : ""));

        return new RequestSigner(method.toString(), resourcePath, creds);
    }
}
