package com.tsi.sig.server.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class TSIEncoder extends BCryptPasswordEncoder {
    public TSIEncoder() {
    }

    public static String encode(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            String rawAndSalt = plainText + "TSI";
            md.update(rawAndSalt.getBytes());
            byte[] byteData = md.digest();
            StringBuffer hexString = new StringBuffer();

            for(int i = 0; i < byteData.length; ++i) {
                String hex = Integer.toHexString(255 & byteData[i]);
                if (hex.length() == 1) {
                    hexString.append('0');
                }

                hexString.append(hex);
            }

            return hexString.toString();
        } catch (NoSuchAlgorithmException ex) {
//            var7.printStackTrace();
            log.error("TSIEncoder - NoSuchAlgorithmException");
            throw new RuntimeException();
        }
    }

    public static Boolean matches(String plainText, String encoded) {
        return encode(plainText).equals(encoded);
    }
}
