package com.fastbee.deviceData.api.devlink.service;

import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;


@Component
public class DevLinkAuthorizationService {

    private final static String ak = "suibin";

    private final static String sk = "MZALH5WB";

    private final static String authId  = "23";

    private final static String BASE_URL = "https://plat.developlink.cloud/prod-api/iot/data/forward";


    public String getBaseUrl(){
        return BASE_URL;
    }

    public String getAuth(){
        String sign;
//        long time = 1731480451430L;
        long time = System.currentTimeMillis();
        String message = "ak=" + ak + "&authId=" + authId + "&time=" + time;
        try {
            SecretKeySpec keySpec = new SecretKeySpec(
                    sk.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(keySpec);
            byte[] rawHmac = mac.doFinal(message.getBytes(StandardCharsets.UTF_8));
            sign = DatatypeConverter.printHexBinary(rawHmac).toLowerCase();
//            System.out.println("d6dbca6837dcfec70954b7261eb6dfadc06fcdfdb771d86ee901ab4823bbb33c");
            System.err.println("result:"+sign);
        } catch (Exception e) {
            throw new RuntimeException("Unable to generate HMAC : " + e.getMessage(), e);
        }
      return "?ak="+ak+"&time="+time+"&sign="+sign+"&authId="+authId;
    }

    public static void main(String[] args) {
        DevLinkAuthorizationService de = new DevLinkAuthorizationService();
        de.getAuth();
        System.out.println(de.getBaseUrl()+de.getAuth());

    }
}
