package com.dittomart.meatsbhavan.util;

import android.util.Base64;

import androidx.annotation.Nullable;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class HashGenerationUtils {

    public static String generateHashFromSDK(String hashData, String salt, @Nullable String merchantSecretKey) {
        if (merchantSecretKey == null || merchantSecretKey.isEmpty()) {
            return calculateHash(hashData + salt);
        } else {
            return calculateHmacSha1(hashData, merchantSecretKey);
        }
    }

    public static String generateV2HashFromSDK(String hashString, String salt) {
        return calculateHmacSha256(hashString, salt);
    }

    private static String calculateHash(String hashString) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
            messageDigest.update(hashString.getBytes());
            byte[] mdbytes = messageDigest.digest();
            return getHexString(mdbytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String calculateHmacSha1(String hashString, String key) {
        try {
            String type = "HmacSHA1";
            SecretKeySpec secret = new SecretKeySpec(key.getBytes(), type);
            Mac mac = Mac.getInstance(type);
            mac.init(secret);
            byte[] bytes = mac.doFinal(hashString.getBytes());
            return getHexString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String getHexString(byte[] data) {
        // Create Hex String
        StringBuilder hexString = new StringBuilder();
        for (byte aMessageDigest : data) {
            String h = Integer.toHexString(0xFF & aMessageDigest);
            while (h.length() < 2) {
                h = "0" + h;
            }
            hexString.append(h);
        }
        return hexString.toString();
    }

    private static String calculateHmacSha256(String hashString, String salt) {
        try {
            String type = "HmacSHA256";
            SecretKeySpec secret = new SecretKeySpec((salt != null ? salt : "").getBytes(), type);
            Mac mac = Mac.getInstance(type);
            mac.init(secret);
            byte[] bytes = mac.doFinal(hashString.getBytes());
            return Base64.encodeToString(bytes, Base64.NO_WRAP);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

