package xml.rooms;

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

import javax.xml.XMLConstants;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import xml.pomoce.Args;

public class CountSeats_Stax_Stream {
	private int sum = 0;
	XMLStreamReader reader;

	public static void main(String[] args) {
		args = Args.argsOrDefault(args, "rooms.xml");
		String input = args[0];
		try {
			CountSeats_Stax_Stream program = new CountSeats_Stax_Stream();
			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.createXMLStreamReader(new FileInputStream(fileName));
		while (reader.hasNext()) {
			if (reader.isStartElement() && "rooms".equals(reader.getLocalName())) {
				this.processRooms();
			}
			reader.next();
		}
		return sum;
	}

	private void processRooms() throws XMLStreamException {
		while (reader.hasNext()) {
			if (reader.isStartElement() && "room".equals(reader.getLocalName())) {
				this.processRoom();
			} else if (reader.isEndElement() && "rooms".equals(reader.getLocalName())) {
				return;
			}
			reader.next();
		}
	}

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

		while (reader.hasNext()) {
			if (reader.isStartElement() && "equipment".equals(reader.getLocalName())) {
				String projector = reader.getAttributeValue(XMLConstants.NULL_NS_URI, "projector");
				if ("true".equals(projector) || "1".equals(projector)) {
					hasProjector = true;
				}
			} else if (hasProjector && reader.isStartElement() && "seats".equals(reader.getLocalName())) {
				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 (reader.isEndElement() && "room".equals(reader.getLocalName())) {
				return;
			}
			reader.next();
		}
	}
}
