package speiger.src.coreengine.assets.impl.parsers;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Map;
import java.util.zip.CRC32C;

import speiger.src.coreengine.assets.api.IAssetParser;

public class Checksums {
	public static final IAssetParser<String> CRC = new CRC();
	public static final IAssetParser<String> SHA_256 = new SHA256();
	
	public static class CRC implements IAssetParser<String> {
		@Override
		public String parse(Path path) throws IOException {
			Map<String, Object> files = Files.readAttributes(path, "*");
			if(files.containsKey("crc")) return Long.toHexString(((Long)files.get("crc")) & 0xFFFFFFFFL);
			CRC32C crc = new CRC32C();
			crc.update(Files.readAllBytes(path));
			return Long.toHexString(crc.getValue());
		}
	}
	
	public static class SHA256 implements IAssetParser<String> {
		@Override
		public String parse(Path path) throws IOException {
            try {
				MessageDigest digest = MessageDigest.getInstance("SHA-256");
				digest.update(Files.readAllBytes(path));
				return Base64.getEncoder().encodeToString(digest.digest());
			}
			catch(NoSuchAlgorithmException e) { e.printStackTrace(); }
			return null;
		}
	}
}
