package data;

public class Offer {
	float area;

	float price;

	float areaPrice;

	int strPos;

	final String AREA_STR = "krunt", PRICE_STR = "EEK";

	final int FORWARD = 1, BACKWARD = -1, SQM = 1, HA = 2;

	String getNumberStr(String src, int start, int dir) {
		String s = "";
		for (strPos = start;; strPos += dir) {
			char c = src.charAt(strPos);
			if (Character.isDigit(c)) {
				s += c;
			} else if (c == ',') {
				s += '.';
			} else if (!(c == ' ' || c == 65533)) {// 65533 - some weird space
				// System.out.println("Found char " + c + "(" + (int) c + "), breaking search");
				break;
			}
		}
		return s;
	}

	void findArea(String line) {
		strPos = line.indexOf(AREA_STR) + AREA_STR.length();
		if (strPos == AREA_STR.length()) {
			// area not found
			area = 0;
		} else {
			String areaStr = getNumberStr(line, strPos, FORWARD);
			// strPos++;
			try {
				area = Float.parseFloat(areaStr);
			} catch (NumberFormatException e) {
				area = 0;
			}
			if (line.charAt(strPos) == 'h') {
				area *= 10000;
			} else {
				// System.out.println("Area not in HA's but in " + line.charAt(strPos));
			}
		}
		// System.out.println("Found area: " + area + " " + strPos);
	}

	void findPrice(String line) {
		strPos = line.indexOf(PRICE_STR);
		if (strPos != -1) {
			// System.out.println("Getting price, pos " + strPos + " " + line.charAt(strPos - 1));
			String priceStr = getNumberStr(line, strPos - 1, BACKWARD);
			String tmp = "";
			for (int i = priceStr.length() - 2; i >= 0; i--) {// skip comma after some prices
				tmp += priceStr.charAt(i);
			}
			priceStr = tmp;
			price = Float.parseFloat(priceStr);
			areaPrice = price / area;
			if (areaPrice == Float.POSITIVE_INFINITY) {
				areaPrice = 0.0f;
			}
			// System.out.println("Price: " + price + " " + areaPrice + " per sqm");
		}
	}

	public Offer(String line) {
		// System.out.println("Parsing offering " + line);
		findArea(line);
		findPrice(line);
	}

	public float getArea() {
		return area;
	}

	public void setArea(float area) {
		this.area = area;
	}

	public float getAreaPrice() {
		return areaPrice;
	}

	public void setAreaPrice(float areaPrice) {
		this.areaPrice = areaPrice;
	}

	public float getPrice() {
		return price;
	}

	public void setPrice(float price) {
		this.price = price;
	}

	public String toString() {
		return "Offering, area: " + area + " Price: " + price + " Area price: " + areaPrice;
	}
}