package cn.reghao.oss.sdk;

import cn.reghao.jutil.jdk.result.WebResult;
import cn.reghao.jutil.jdk.serializer.JsonConverter;
import cn.reghao.oss.sdk.model.OssConsoleConfig;
import cn.reghao.oss.api.dto.ObjectChannel;
import cn.reghao.oss.api.dto.ObjectInfo;
import cn.reghao.oss.api.dto.ServerInfo;
import cn.reghao.oss.api.dto.StoreProperties;
import cn.reghao.oss.api.dto.media.*;
import cn.reghao.oss.api.rest.UploadFileRet;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author reghao
 * @date 2024-02-23 21:47:39
 */
public class OssConsoleClient {
    private final HttpClient httpClient = HttpClient.newBuilder().build();
    private final String endpoint;
    private String token;

    public OssConsoleClient(OssConsoleConfig ossProperties) throws Exception {
        this.endpoint = ossProperties.getConsoleUrl();
        auth(ossProperties.getAccessKeyId(), ossProperties.getAccessKeySecret());
    }

    public OssConsoleClient(String endpoint) {
        this.endpoint = endpoint;
    }

    // ****************************************************************************************************************
    // oss-console 认证接口
    // ****************************************************************************************************************
    private void auth(String accessKeyId, String accessKeySecret) throws Exception {
        MultiPartBodyPublisher publisher = new MultiPartBodyPublisher()
                .addPart("accessKeyId", accessKeyId)
                .addPart("accessKeySecret", accessKeySecret);

        String api = String.format("%s/api/oss/key/auth", endpoint);
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI(api))
                .version(HttpClient.Version.HTTP_1_1)
                .header("content-type", "multipart/form-data; boundary=" + publisher.getBoundary())
                .POST(publisher.build())
                .build();

        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        int statusCode = httpResponse.statusCode();
        String body = httpResponse.body();
        if (statusCode != 200) {
            String errMsg = String.format("%s -> %s", statusCode, body);
            throw new Exception(errMsg);
        }

        Type type = new TypeToken<WebResult<String>>(){}.getType();
        WebResult<String> webResult = JsonConverter.jsonToObject(body, type);
        if (webResult.getCode() != 0) {
            String errMsg = String.format("%s - %s", webResult.getCode(), webResult.getMsg());
            throw new Exception(errMsg);
        }

        this.token = webResult.getData();
    }

    // ****************************************************************************************************************
    // oss-store 相关接口
    // ****************************************************************************************************************
    public ServerInfo getUploadStore(int channelId) throws Exception {
        String api = String.format("%s/api/oss/upload/store?channelId=%s", endpoint, channelId);
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI(api))
                .header("authorization", "Bearer " + token)
                .version(HttpClient.Version.HTTP_1_1)
                .GET()
                .build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        int statusCode = httpResponse.statusCode();
        String body = httpResponse.body();
        if (statusCode != 200) {
            String errMsg = String.format("%s -> %s", statusCode, body);
            throw new Exception(errMsg);
        }

        Type type = new TypeToken<WebResult<ServerInfo>>(){}.getType();
        WebResult<ServerInfo> webResult = JsonConverter.jsonToObject(body, type);
        if (webResult.getCode() != 0) {
            String errMsg = String.format("%s - %s", webResult.getCode(), webResult.getMsg());
            throw new Exception(errMsg);
        }

        return webResult.getData();
    }

    public ObjectInfo getChannelScope(int channelId) throws Exception {
        String api = String.format("%s/api/oss/channel/scope?channelId=%s", endpoint, channelId);
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI(api))
                .header("authorization", "Bearer " + token)
                .version(HttpClient.Version.HTTP_1_1)
                .GET()
                .build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        int statusCode = httpResponse.statusCode();
        String body = httpResponse.body();
        if (statusCode != 200) {
            String errMsg = String.format("%s -> %s", statusCode, body);
            throw new Exception(errMsg);
        }

        Type type = new TypeToken<WebResult<ObjectInfo>>(){}.getType();
        WebResult<ObjectInfo> webResult = JsonConverter.jsonToObject(body, type);
        if (webResult.getCode() != 0) {
            String errMsg = String.format("%s - %s", webResult.getCode(), webResult.getMsg());
            throw new Exception(errMsg);
        }

        return webResult.getData();
    }

    public void setObjectScope(int channelId, String objectId, int scope) throws Exception {
        Map<String, String> formData = new HashMap<>();
        formData.put("channelId", channelId+"");
        formData.put("scope", scope+"");
        formData.put("objectId", objectId);

        String api = String.format("%s/api/oss/object/scope/object", endpoint);
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI(api))
                .header("authorization", "Bearer " + token)
                .headers("content-type", "application/x-www-form-urlencoded")
                .version(HttpClient.Version.HTTP_1_1)
                .POST(HttpRequest.BodyPublishers.ofString(getFormDataAsString(formData)))
                .build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        int statusCode = httpResponse.statusCode();
        String body = httpResponse.body();
        if (statusCode != 200) {
            String errMsg = String.format("%s -> %s", statusCode, body);
            throw new Exception(errMsg);
        }

        Type type = new TypeToken<WebResult<String>>(){}.getType();
        WebResult<String> webResult = JsonConverter.jsonToObject(body, type);
        if (webResult.getCode() != 0) {
            String errMsg = String.format("%s - %s", webResult.getCode(), webResult.getMsg());
            throw new Exception(errMsg);
        }
    }

    private String getFormDataAsString(Map<String, String> formData) {
        StringBuilder formBodyBuilder = new StringBuilder();
        for (Map.Entry<String, String> singleEntry : formData.entrySet()) {
            if (formBodyBuilder.length() > 0) {
                formBodyBuilder.append("&");
            }
            formBodyBuilder.append(URLEncoder.encode(singleEntry.getKey(), StandardCharsets.UTF_8));
            formBodyBuilder.append("=");
            formBodyBuilder.append(URLEncoder.encode(singleEntry.getValue(), StandardCharsets.UTF_8));
        }
        return formBodyBuilder.toString();
    }

    public void deleteByObjectId(int channelId, String objectId) throws Exception {
        Map<String, String> formData = new HashMap<>();
        formData.put("channelId", channelId+"");
        formData.put("objectId", objectId);

        String api = String.format("%s/api/oss/object/delete/id", endpoint);
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI(api))
                .header("authorization", "Bearer " + token)
                .headers("content-type", "application/x-www-form-urlencoded")
                .version(HttpClient.Version.HTTP_1_1)
                .POST(HttpRequest.BodyPublishers.ofString(getFormDataAsString(formData)))
                .build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        int statusCode = httpResponse.statusCode();
        String body = httpResponse.body();
        if (statusCode != 200) {
            String errMsg = String.format("%s -> %s", statusCode, body);
            throw new Exception(errMsg);
        }

        Type type = new TypeToken<WebResult<String>>(){}.getType();
        WebResult<String> webResult = JsonConverter.jsonToObject(body, type);
        if (webResult.getCode() != 0) {
            String errMsg = String.format("%s - %s", webResult.getCode(), webResult.getMsg());
            throw new Exception(errMsg);
        }
    }

    public void deleteByObjectUrl(String objectUrl) throws Exception {
        Map<String, String> formData = new HashMap<>();
        formData.put("objectUrl", objectUrl);

        String api = String.format("%s/api/oss/object/delete/url", endpoint);
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI(api))
                .header("authorization", "Bearer " + token)
                .headers("content-type", "application/x-www-form-urlencoded")
                .version(HttpClient.Version.HTTP_1_1)
                .POST(HttpRequest.BodyPublishers.ofString(getFormDataAsString(formData)))
                .build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        int statusCode = httpResponse.statusCode();
        String body = httpResponse.body();
        if (statusCode != 200) {
            String errMsg = String.format("%s -> %s", statusCode, body);
            throw new Exception(errMsg);
        }

        Type type = new TypeToken<WebResult<String>>(){}.getType();
        WebResult<String> webResult = JsonConverter.jsonToObject(body, type);
        if (webResult.getCode() != 0) {
            String errMsg = String.format("%s - %s", webResult.getCode(), webResult.getMsg());
            throw new Exception(errMsg);
        }
    }

    public ObjectInfo getObjectInfo(int channelId, String objectId) throws Exception {
        String api = String.format("%s/api/oss/object/info?channelId=%s&objectId=%s", endpoint, channelId, objectId);
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI(api))
                .header("authorization", "Bearer " + token)
                .version(HttpClient.Version.HTTP_1_1)
                .GET()
                .build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        int statusCode = httpResponse.statusCode();
        String body = httpResponse.body();
        if (statusCode != 200) {
            String errMsg = String.format("%s -> %s", statusCode, body);
            throw new Exception(errMsg);
        }

        Type type = new TypeToken<WebResult<ObjectInfo>>(){}.getType();
        WebResult<ObjectInfo> webResult = JsonConverter.jsonToObject(body, type);
        if (webResult.getCode() != 0) {
            String errMsg = String.format("%s - %s", webResult.getCode(), webResult.getMsg());
            throw new Exception(errMsg);
        }

        return webResult.getData();
    }

    public String getSignedUrl(int channelId, String objectId) throws Exception {
        String api = String.format("%s/api/oss/object/url?channelId=%s&objectId=%s", endpoint, channelId, objectId);
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI(api))
                .header("authorization", "Bearer " + token)
                .version(HttpClient.Version.HTTP_1_1)
                .GET()
                .build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        int statusCode = httpResponse.statusCode();
        String body = httpResponse.body();
        if (statusCode != 200) {
            String errMsg = String.format("%s -> %s", statusCode, body);
            throw new Exception(errMsg);
        }

        Type type = new TypeToken<WebResult<String>>(){}.getType();
        WebResult<String> webResult = JsonConverter.jsonToObject(body, type);
        if (webResult.getCode() != 0) {
            String errMsg = String.format("%s - %s", webResult.getCode(), webResult.getMsg());
            throw new Exception(errMsg);
        }

        return webResult.getData();
    }

    public VideoInfo getVideoInfo(int channelId, String objectId) throws Exception {
        String api = String.format("%s/api/oss/object/video/info?channelId=%s&objectId=%s", endpoint, channelId, objectId);
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI(api))
                .header("authorization", "Bearer " + token)
                .version(HttpClient.Version.HTTP_1_1)
                .GET()
                .build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        int statusCode = httpResponse.statusCode();
        String body = httpResponse.body();
        if (statusCode != 200) {
            String errMsg = String.format("%s -> %s", statusCode, body);
            throw new Exception(errMsg);
        }

        Type type = new TypeToken<WebResult<VideoInfo>>(){}.getType();
        WebResult<VideoInfo> webResult = JsonConverter.jsonToObject(body, type);
        if (webResult.getCode() != 0) {
            String errMsg = String.format("%s - %s", webResult.getCode(), webResult.getMsg());
            throw new Exception(errMsg);
        }

        return webResult.getData();
    }

    public ImageInfo getImageInfo(int channelId, String objectId) throws Exception {
        String api = String.format("%s/api/oss/object/video/image?channelId=%s&objectId=%s", endpoint, channelId, objectId);
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI(api))
                .header("authorization", "Bearer " + token)
                .headers("content-type", "application/x-www-form-urlencoded")
                .version(HttpClient.Version.HTTP_1_1)
                .GET()
                .build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        int statusCode = httpResponse.statusCode();
        String body = httpResponse.body();
        if (statusCode != 200) {
            String errMsg = String.format("%s -> %s", statusCode, body);
            throw new Exception(errMsg);
        }

        Type type = new TypeToken<WebResult<ImageInfo>>(){}.getType();
        WebResult<ImageInfo> webResult = JsonConverter.jsonToObject(body, type);
        if (webResult.getCode() != 0) {
            String errMsg = String.format("%s - %s", webResult.getCode(), webResult.getMsg());
            throw new Exception(errMsg);
        }

        return webResult.getData();
    }

    public ConvertedImageInfo getWebpInfo(int channelId, String objectId) throws Exception {
        Map<String, String> formData = new HashMap<>();
        formData.put("channelId", ""+channelId);
        formData.put("objectId", objectId);

        String api = String.format("%s/api/oss/object/image/webp", endpoint);
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI(api))
                .header("authorization", "Bearer " + token)
                .headers("content-type", "application/x-www-form-urlencoded")
                .version(HttpClient.Version.HTTP_1_1)
                .POST(HttpRequest.BodyPublishers.ofString(getFormDataAsString(formData)))
                .build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        int statusCode = httpResponse.statusCode();
        String body = httpResponse.body();
        if (statusCode != 200) {
            String errMsg = String.format("%s -> %s", statusCode, body);
            throw new Exception(errMsg);
        }

        Type type = new TypeToken<WebResult<ConvertedImageInfo>>(){}.getType();
        WebResult<ConvertedImageInfo> webResult = JsonConverter.jsonToObject(body, type);
        if (webResult.getCode() != 0) {
            String errMsg = String.format("%s - %s", webResult.getCode(), webResult.getMsg());
            throw new Exception(errMsg);
        }

        return webResult.getData();
    }

    public AudioInfo getAudioInfo(int channelId, String objectId) throws Exception {
        String api = String.format("%s/api/oss/object/audio/info/?channelId=%s&objectId=%s", endpoint, channelId, objectId);
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI(api))
                .header("authorization", "Bearer " + token)
                .version(HttpClient.Version.HTTP_1_1)
                .GET()
                .build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        int statusCode = httpResponse.statusCode();
        String body = httpResponse.body();
        if (statusCode != 200) {
            String errMsg = String.format("%s -> %s", statusCode, body);
            throw new Exception(errMsg);
        }

        Type type = new TypeToken<WebResult<AudioInfo>>(){}.getType();
        WebResult<AudioInfo> webResult = JsonConverter.jsonToObject(body, type);
        if (webResult.getCode() != 0) {
            String errMsg = String.format("%s - %s", webResult.getCode(), webResult.getMsg());
            throw new Exception(errMsg);
        }

        return webResult.getData();
    }

    // ****************************************************************************************************************
    // 音视频转码相关接口
    // ****************************************************************************************************************
    public void convertAudio(String audioFileId) throws Exception {
        String api = String.format("%s/api/oss/object/convert/audio/%s", endpoint, audioFileId);
        convert(api);
    }

    public void convertVideo(String videoFileId) throws Exception {
        String api = String.format("%s/api/oss/object/convert/video/%s", endpoint, videoFileId);
        convert(api);
    }

    private void convert(String api) throws Exception {
        MultiPartBodyPublisher publisher = new MultiPartBodyPublisher();
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI(api))
                .header("authorization", "Bearer " + token)
                .version(HttpClient.Version.HTTP_1_1)
                .POST(publisher.build())
                .build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        int statusCode = httpResponse.statusCode();
        String body = httpResponse.body();
        if (statusCode != 200) {
            String errMsg = String.format("%s -> %s", statusCode, body);
            throw new Exception(errMsg);
        }

        Type type = new TypeToken<WebResult<String>>(){}.getType();
        WebResult<String> webResult = JsonConverter.jsonToObject(body, type);
        if (webResult.getCode() != 0) {
            String errMsg = String.format("%s - %s", webResult.getCode(), webResult.getMsg());
            throw new Exception(errMsg);
        }
    }

    public UploadFileRet uploadFile(int channelId, File file) throws Exception {
        ServerInfo serverInfo = getUploadStore(channelId);
        if (serverInfo == null) {
            throw new Exception("获取 server_info 失败");
        }
        String ossUrl = serverInfo.getOssUrl();
        String token = serverInfo.getToken();

        OssStoreClient ossStoreClient = new OssStoreClient(ossUrl);
        UploadFileRet uploadFileRet = ossStoreClient.postObjectWithJdkHttp(file, channelId, token);
        return uploadFileRet;
    }
}
