package com.ease.gsms.server.model.util;

import org.apache.commons.lang3.builder.CompareToBuilder;

import javax.xml.bind.DatatypeConverter;
import java.nio.ByteBuffer;
import java.util.Arrays;

public class MD5Hash implements Comparable<MD5Hash> {

    private byte[] hash;

    public MD5Hash(byte[] hash) {

        this.hash = hash;

    }

    @Override
    public int compareTo(MD5Hash another) {

        return new CompareToBuilder().append(hash, another.hash).toComparison();

    }

    public static MD5Hash fromBytes(byte[] hash) {

        return new MD5Hash(hash);

    }

    public static MD5Hash fromHexString(String hash) {

        return fromBytes(DatatypeConverter.parseHexBinary(hash));

    }


    public Long getHigh() {

        return ByteBuffer.wrap(hash, 0, 8).getLong();

    }

    public Long getLow() {

        return ByteBuffer.wrap(hash, 8, 8).getLong();

    }

    public String toHexString() {

        return DatatypeConverter.printHexBinary(hash);

    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MD5Hash md5Hash = (MD5Hash) o;
        return Arrays.equals(hash, md5Hash.hash);
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(hash);
    }

}
