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

public class MutableInteger {
	
	private int value;
	
	public int getValue() {
		return value;
	}

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

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

	public MutableInteger(int value) {
		this.value = value;
	}

	public boolean parseInt(String s, boolean positive) {
		if(s == null || s.isEmpty()) {
			return false;
		}
		int 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 parseInt(String s) {
		return parseInt(s, false);
	}
	
	public boolean parsePositiveInt(String s) {
		return parseInt(s, true);
	}
	
	public static int parseInt(String s, boolean positive, int defaultValue) {
		MutableInteger i = new MutableInteger(defaultValue);
		i.parseInt(s, positive);
		return i.getValue();
	}
	
	public static int parseInt(String s, int defaultValue) {
		return parseInt(s, false, defaultValue);
	}
	
	public static int parsePositiveInt(String s, int defaultValue) {
		return parseInt(s, true, defaultValue);
	}
}
