package przyklady_z_uczelni.rooms;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import util.Args;

public class CountSeats_DOM_Specialized {
	private int sum = 0;
	
	public static void main(String[] args) {
		args = Args.argsOrDefault(args, "rooms.xml");
		String input = args[0];
		try {
			CountSeats_DOM_Specialized program = new CountSeats_DOM_Specialized();
			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 ParserConfigurationException, SAXException, IOException {
		System.out.println("Starting with file " + fileName);

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = dbf.newDocumentBuilder();
		Document doc = builder.parse(fileName);
		Element rooms = doc.getDocumentElement();
		if("rooms".equals(rooms.getNodeName()))
			this.processRooms(rooms);
		return sum;
	}

	private void processRooms(Element roomsElem) {
		NodeList list = roomsElem.getElementsByTagName("room");
		for(int i=0; i < list.getLength(); ++i) {
			this.processRoom(list.item(i));
		}
	}

	private void processRoom(Node roomNode) {
		Element roomElem = (Element) roomNode;

		boolean hasProjector = false;	
		Element seatsElem = null;
		Element equipmentElem = (Element) roomElem.getElementsByTagName("equipment").item(0);
		
		if(equipmentElem != null) {
			String projector = equipmentElem.getAttribute("projector");
			if("true".equals(projector) || "1".equals(projector)) {
				hasProjector = true;	
		}	}
		if(hasProjector) {
			seatsElem = (Element) roomElem.getElementsByTagName("seats").item(0);
		}
		if(seatsElem != null) {
			String seatsString = seatsElem.getTextContent();
			try {
				int seats = Integer.parseInt(seatsString);
				sum += seats;
			} catch (NumberFormatException e) {
				// Incorrect number format is silently ignored (sum is not increased).
			}
		}
	}
}
