/*
 * Copyright (C) 2024 Baidu, Inc. All Rights Reserved.
 */
package com.baidu.ai.sample.cloudrender;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.codec.digest.DigestUtils;
import org.json.JSONObject;

public abstract class CloudRenderRequest {
    private String appKey;
    private String appSecret;
    private String desKey;
    protected String[] cloudPhoneInstanceIds = {"VM010150254141"};
    protected String instanceId = "9999";

    long nonce;

    public CloudRenderRequest(String appKey, String appSecret, String desKey) {
        this.appKey = appKey;
        this.appSecret = appSecret;
        this.desKey = desKey;
        this.nonce = System.currentTimeMillis();
    }

    public void setAIInstanceId(String instanceId) {
        this.instanceId = instanceId;
    }

    protected abstract String getPath();

    public String generateApiUrl() {
        // 接口版本号，现在有2和3两种版本的接口，具体按照接口文档上的版本号
        String authVer = "3";
        // 生成方法签名
        String paramsStr = "appkey" + appKey +
                "auth_ver" + authVer +
                "nonce" + System.currentTimeMillis() + appSecret;
        String sign = DigestUtils.md5Hex(paramsStr.getBytes(StandardCharsets.UTF_8));
        // 拼接公共参数到URL
        String apiUrl = "https://platform.armvm.com/" + getPath() + "?s=" + sign
                + "&appkey=" + appKey + "&auth_ver=" + authVer + "&nonce=" + nonce;
        return apiUrl;
    }

    protected abstract String generateRequestParam();

    protected void setCloudPhoneInstanceIds(String[] cloudPhoneInstanceIds) {
        this.cloudPhoneInstanceIds = cloudPhoneInstanceIds;
    }

    public String generateEncryptBody() {
        String requestParam = generateRequestParam();
        String encryptBody = "";
        try {
            // 请求参数加密
            Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede");
            SecretKey secretKey =
                    skf.generateSecret(new DESedeKeySpec(desKey.getBytes(StandardCharsets.UTF_8)));
            ByteBuffer byteBuffer = ByteBuffer.allocate(8);
            byteBuffer.order(ByteOrder.BIG_ENDIAN);
            byteBuffer.putLong(nonce);
            byte[] iv = byteBuffer.array();
            IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
            byte[] cipherText = cipher.doFinal(requestParam.getBytes(StandardCharsets.UTF_8));
            String msg = "";
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                msg = Base64.getEncoder().encodeToString(cipherText);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("createTime", nonce);
            map.put("msg", msg);
            encryptBody = new JSONObject(map).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptBody;

    }


}
