package info.knacki.pass.git;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import info.knacki.pass.git.entities.GitObject;
import info.knacki.pass.git.entities.GitPackable;
import info.knacki.pass.git.entities.GitPackableUtil;

public class GitSha1 {
    public static byte[] StringToBytes(String hash) {
        byte[] result = new byte[20];
        int j =0;

        for (int i =0; i +1 < hash.length(); i += 2)
            result[j++] = (byte) Integer.parseInt(hash.substring(i, i+2), 16);
        return result;
    }

    public static String BytesToString(byte[] sha1Bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte i: sha1Bytes)
            sb.append(Integer.toString((i & 0xff) + 0x100, 16).substring(1));
        return sb.toString();
    }

    public static byte[] getRawSha1OfFile(final File f)
    {
        return getRawSha1OfPackable(new GitPackable() {
            @Override
            public eType GetPackableType() {
                return eType.eType_Blob;
            }

            @Override
            public byte[] GetPack() {
                try {
                    return GitObject.GitBlob.GetFilePack(f);
                }
                catch (FileNotFoundException e) {

                }
                catch (IOException e) {

                }
                return null;
            }
        });
    }

    public static byte[] getRawSha1OfPackable(GitPackable obj) {
        try {
            MessageDigest sha1Builder = MessageDigest.getInstance("SHA1");
            byte[] packContent = obj.GetPack();
            if (packContent == null) {
                return new byte[]{};
            }
            sha1Builder.update((GitPackableUtil.GetObjTypeString(obj.GetPackableType()) +" " +packContent.length).getBytes());
            sha1Builder.update(new byte[] { 0 });
            sha1Builder.update(packContent);
            return sha1Builder.digest();
        }
        catch (NoSuchAlgorithmException e) {
            return new byte[]{};
        }
    }

    public static String getSha1OfPackable(GitPackable obj) {
        byte[] raw = getRawSha1OfPackable(obj);
        return raw.length == 0 ? "" : BytesToString(raw);
    }
}
