package cz.senslog.connector.fetch.fieldclimate.auth;



import org.apache.hc.client5.http.utils.Hex;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class AuthenticationService {

    private final AuthConfig authConfig;

    public AuthenticationService(AuthConfig authConfig) {
        this.authConfig = authConfig;
    }


    public String getAccessToken(String seed) {

        String publicKey = authConfig.getPublicKey();
        String privateKey = authConfig.getPrivateKey();
        String contentToSign = seed + publicKey;

        String signature = generateHmacSHA256Signature(contentToSign, privateKey);
        return "hmac " + publicKey + ":" + signature;
    }

    private static String generateHmacSHA256Signature(String data, String key){

        try
        {
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(secretKey);
            return Hex.encodeHexString(mac.doFinal(data.getBytes("UTF-8")));

        } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException e) {
            return "";
        }
    }
}
