package dev.ksan.etfoglasiserver.util;

import dev.ksan.etfoglasiserver.model.Entry;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Objects;

public class HashGenerator {

  public static String hashEntry(Entry entry) {
    String data =
        Objects.toString(entry.getTitle(), "")
            + Objects.toString(entry.getTimePublished(), "")
            + Objects.toString(entry.getParagraph(), "")
            + Objects.toString(entry.getFilepath(), "");

    try {
      final MessageDigest digest = MessageDigest.getInstance("SHA3-256");

      final byte[] hashbytes = digest.digest(data.getBytes(StandardCharsets.UTF_8));

      String sha3Hex = bytesToHex(hashbytes);

      return sha3Hex;
    } catch (Exception e) {
      throw new RuntimeException("Failed to generate hashed id of Entry: " + entry.getTitle());
    }
  }

  private static String bytesToHex(byte[] hash) {
    StringBuilder hexString = new StringBuilder(2 * hash.length);
    for (int i = 0; i < hash.length; i++) {
      String hex = Integer.toHexString(0xff & hash[i]);
      if (hex.length() == 1) {
        hexString.append('0');
      }
      hexString.append(hex);
    }
    return hexString.toString();
  }
}
