package com.wecloud.im.sdk.internal;

import okhttp3.Response;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wecloud.im.sdk.common.ApiResult;
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.RequestParamSigner;
import com.wecloud.im.sdk.common.auth.Credentials;
import com.wecloud.im.sdk.exception.WecloudException;

/**
 *
 * @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 <T> ApiResult<T> doOperation(RequestMessage request) {
        // 请求头签名
        String signature = RequestParamSigner.sign(request.getClientId(), request.getClientId(), this.appKey,
                this.appSecret, request.getPlatform());
        request.addHeader(ImHeaders.WECLOUD_SIGN, signature);
        return send(request);

    }

    @SuppressWarnings("unchecked")
    private <T> ApiResult<T> send(RequestMessage request) {
        try {
            // 组装请求
            Map<String, Object> parameters = BeanUtil.beanToMap(request.getOriginalRequest(), false, true);
            Map<String, String> finalParameters = new HashMap<>();
            parameters.forEach((k, v) -> {
                finalParameters.put(k, v.toString());
            });

            URL endpoint = new URL(apiDomain, request.getEndpoint());
            HttpClient httpClient =
                    HttpClient.builder().url(endpoint).addHeaders(request.getHeaders()).addParams(request.getParameters()).addParams(finalParameters);

            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().toString();
            // 泛型的反序列化
            TypeReference typeRef = new TypeReference<ApiResult<T>>() {
            };
            return (ApiResult<T>) JSON.parseObject(responseBody, typeRef);
        } 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);
    }


}
