package xml.rooms;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.XMLEvent;

import xml.pomoce.Args;

public class CountSeats_Stax_Event {
	private int sum = 0;
	XMLEventReader reader;

	public static void main(String[] args) {
		args = Args.argsOrDefault(args, "rooms.xml");
		String input = args[0];
		try {
			CountSeats_Stax_Event program = new CountSeats_Stax_Event();
			int result = program.countSeats(input);
			System.out.println("Result: " + result);
		} catch (Exception e) {
			System.out.println("Exception! " + e.getMessage());
			e.printStackTrace();
		}
	}

	public int countSeats(String fileName) throws FileNotFoundException, XMLStreamException {
		System.out.println("Starting with file " + fileName);
		XMLInputFactory xif = XMLInputFactory.newInstance();
		reader = xif.createXMLEventReader(new FileInputStream(fileName));
		while (reader.hasNext()) {
			XMLEvent event = reader.nextEvent();
			if (event.isStartElement() && "rooms".equals(event.asStartElement().getName().getLocalPart())) {
				this.processRooms();
			}
		}
		return sum;
	}

	private void processRooms() throws XMLStreamException {
		while (reader.hasNext()) {
			XMLEvent event = reader.nextEvent();
			if (event.isStartElement() && "room".equals(event.asStartElement().getName().getLocalPart())) {
				this.processRoom();
			} else if (event.isEndElement() && "rooms".equals(event.asEndElement().getName().getLocalPart())) {
				return;
			}
		}
	}

	private void processRoom() throws XMLStreamException {
		boolean hasProjector = false;

		while (reader.hasNext()) {
			XMLEvent event = reader.nextEvent();
			if (event.isStartElement() && "equipment".equals(event.asStartElement().getName().getLocalPart())) {
				Attribute projectorEvent = event.asStartElement().getAttributeByName(new QName(XMLConstants.NULL_NS_URI, "projector"));
				if(projectorEvent != null) {
					String projector = projectorEvent.getValue();
					if ("true".equals(projector) || "1".equals(projector)) {
						hasProjector = true;
					}
				}
			} else if (hasProjector && event.isStartElement() && "seats".equals(event.asStartElement().getName().getLocalPart())) {
				String seatsString = reader.getElementText();
				try {
					int seats = Integer.parseInt(seatsString);
					sum += seats;
				} catch (NumberFormatException e) {
					// Incorrect number format is silently ignored (sum is not increased).
				}
			} else if (event.isEndElement() && "room".equals(event.asEndElement().getName().getLocalPart())) {
				return;
			}
		}
	}
}
