package przyklady_z_uczelni.rooms;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class CSHandler_JAXP extends DefaultHandler {
	private int sum = 0;
	private CSHandler_States state = CSHandler_States.OUT;
	private StringBuilder buffer;
	
	public int getSum() {
		return sum;
	}
	
	public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
		switch(state){
		case OUT:
			if("rooms".equals(qName)) {
				state = CSHandler_States.IN_ROOMS;
			}
			break;
		case IN_ROOMS:
			if("room".equals(qName)) {
				state = CSHandler_States.IN_ROOM;
			}
			break;
		case IN_ROOM:
			if("equipment".equals(qName)) {
				String projector = atts.getValue("projector");
				if("true".equals(projector) || "1".equals(projector))
					state = CSHandler_States.IN_ROOM_WITH_PROJECTOR;
			}
			break;
		case IN_ROOM_WITH_PROJECTOR:
			if("seats".equals(qName)) {
				buffer = new StringBuilder();
				state = CSHandler_States.IN_SEATS;
			}
			break;
		case IN_SEATS:
			// Do nothing
		}
	}

	public void endElement(String uri, String localName, String qName) throws SAXException {
		switch(state){
		case IN_SEATS:
			try {
				int value = Integer.parseInt(buffer.toString());
				sum += value;
			} catch (NumberFormatException e) {
				// Incorrect number format is silently ignored (sum is not increased).
			}
			buffer = null;
			state = CSHandler_States.IN_ROOM;
			break;
		case IN_ROOM:
		case IN_ROOM_WITH_PROJECTOR:
			if("room".equals(qName)) {
				state = CSHandler_States.IN_ROOMS;
			}
			break;
		case IN_ROOMS:
			if("rooms".equals(qName)) {
				state = CSHandler_States.OUT;
			}
			break;
		case OUT:
			// Do nothing
		}
	}

	public void characters(char[] ch, int start, int length) throws SAXException {
		if(state == CSHandler_States.IN_SEATS) {
			buffer.append(ch, start, length);
		}
	}
}
