package cz.muni.fi.lasaris.sbms.data.providers.bacnet.util;

public class MutableLong {
private long value;
	
	public long getValue() {
		return value;
	}

	public void setValue(long value) {
		this.value = value;
	}

	public MutableLong() {
		this.value = 0;
	}

	public MutableLong(long value) {
		this.value = value;
	}

	public boolean parseLong(String s, boolean positive) {
		if(s == null || s.isEmpty()) {
			return false;
		}
		long num = 0;
		boolean isNumeric = true;
		boolean isNegative = false;
		int pos = 0;
		if(s.charAt(0) == '-') {
			if(positive) {
				// premature end of parsing - we want only positive integers
				return false;
			}
			isNegative = true;
			pos = 1;
		}
		
		while(isNumeric && pos < s.length()) {
			num *= 10;
			char c = s.charAt(pos);
			if(c >= '0' && c <= '9') {
				num += c - '0';
			} else {
				isNumeric = false;
			}
			pos+=1;
		}
		if(isNegative) {
			num*= -1;
		}
		if(isNumeric) {
			this.value = num;
			return true;
		}
		return false;
	}
	
	public boolean parseLong(String s) {
		return parseLong(s, false);
	}
	
	public boolean parsePositiveLong(String s) {
		return parseLong(s, true);
	}
	
	public static long parseLong(String s, boolean positive, long defaultValue) {
		MutableLong i = new MutableLong(defaultValue);
		i.parseLong(s, positive);
		return i.getValue();
	}
	
	public static long parsePositiveLong(String s, long defaultValue) {
		return parseLong(s, true, defaultValue);
	}
	
	public static long parseLong(String s, long defaultValue) {
		return parseLong(s, false, defaultValue);
	}
}
