package sgc.portal.base.util;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

/**
 * The type File to hex.
 *
 * @author beomgeun.lee
 * @version 2019.11.11
 * @since JDK1.8
 */
@Slf4j
public class FileToHex {

    private static String BASE64_PREFIX = "data:image/bmp;base64,";
    /**
     * Convert to hex string.
     *
     * @param file the file
     * @return the string
     * @throws IOException the io exception
     */
    public static String convertToHex(File file) throws IOException {

        int value;
        StringBuilder sbHex = new StringBuilder();

        try(InputStream is = Files.newInputStream(file.toPath())) {

            while ((value = is.read()) != -1) {
                sbHex.append(String.format("%02x", value));
            }
        }

        return sbHex.toString();
    }

    public static String hexStringToImgString(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ( (Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16) );
        }

        String imgString = BASE64_PREFIX + Base64.encode(data);
        return imgString;
    }

}
