/**
 *  #%L
 *  geoserver-sync-core
 *  %%
 *  Copyright (C) 2013 Moebius Solutions Inc.
 *  %%
 *  This program is free software: you can redistribute it and/or
 *  modify it under the terms of the Apache License v2.0 as
 *  published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  Apache License v2.0 for more details.
 *
 *  You should have received a copy of the Apache License v2.0
 *  along with this program.  If not, see
 *  <http://www.apache.org/licenses/LICENSE-2.0.html>.
 *  #L%
 *
 */
package com.moesol.geoserver.sync.core;



import java.util.Arrays;

import com.moesol.geoserver.sync.grouper.GroupPosition;

/**
 * Value object to hold hash result.
 */
public class Sha1Value implements Comparable<Sha1Value> {
	private final byte[] m_digest;
	
	public Sha1Value(byte[] digest) {
		m_digest = digest;
	}
	
	/**
	 * Inverse of toString.
	 * @param string
	 */
	public Sha1Value(String string) {
		m_digest = ByteArrayHelper.fromHex(string);
	}

	/**
	 * @return Digest bytes. Do not change returned.
	 */
	public byte[] get() {
		return m_digest;
	}

	public String toString() {
		return ByteArrayHelper.toHex(m_digest);
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + Arrays.hashCode(m_digest);
		return result;
	}

	// Generated by eclipse
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Sha1Value other = (Sha1Value) obj;
		if (!Arrays.equals(m_digest, other.m_digest))
			return false;
		return true;
	}
	
	public boolean isPrefixMatch(GroupPosition prefix) {
		return isPrefixMatch(prefix.get());
	}

	public boolean isPrefixMatch(byte[] prefix) {
		for (int i = 0; i < prefix.length; i++) {
			if (prefix[i] != m_digest[i]) {
				return false;
			}
		}
		return true;
	}
	
	public void copyPrefixTo(byte[] out) {
		System.arraycopy(m_digest, 0, out, 0, out.length);
	}

	@Override
	public int compareTo(Sha1Value o) {
		byte[] left = get();
		byte[] right = o.get();
		
		int i = 0;
		while (i < left.length) {
			if (i == right.length) {
				return 1;
			}
			int diff = (0xFF & left[i]) - (0xFF & right[i]);
			if (diff != 0) {
				return diff;
			}
			i++;
		}
		if (i < right.length) {
			return -1;
		}
		
		return 0;
	}

}
