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.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import util.Args;

public class CountSeats_DOM_Generic {
	private int sum = 0;
	
	public static void main(String[] args) {
		args = Args.argsOrDefault(args, "rooms.xml");
		String input = args[0];
		try {
			CountSeats_DOM_Generic program = new CountSeats_DOM_Generic();
			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);
		for(Node node = doc.getFirstChild(); node != null; node = node.getNextSibling()) {
			if(node.getNodeType() == Node.ELEMENT_NODE
					&& "rooms".equals(node.getNodeName())) {
				this.processRooms(node);
			}
		}
		return sum;
	}

	private void processRooms(Node roomsNode) {
		for(Node node = roomsNode.getFirstChild(); node != null; node = node.getNextSibling()) {
			if(node.getNodeType() == Node.ELEMENT_NODE
					&& "room".equals(node.getNodeName())) {
				this.processRoom(node);
			}
		}
	}

	private void processRoom(Node roomNode) {
		boolean hasProjector = false;

		Node seatsNode = null;
		Node equipmentNode = null;
		
		for(Node node = roomNode.getFirstChild(); node != null; node = node.getNextSibling()) {
			// searching for <equipment> node
			if(node.getNodeType() == Node.ELEMENT_NODE
					&& "equipment".equals(node.getNodeName())) {
				equipmentNode = node;
				break;
			}
		}
		if(equipmentNode != null) {
			NamedNodeMap equipmentAttributes = equipmentNode.getAttributes();
			Node projectorNode = equipmentAttributes.getNamedItem("projector");
			if(projectorNode != null) {
				String projector = projectorNode.getNodeValue().trim();
				if("true".equals(projector) || "1".equals(projector)) {
					hasProjector = true;	
		}	}	}
		if(hasProjector) {
			for(Node node = roomNode.getFirstChild(); node != null; node = node.getNextSibling()) {
				// searching for <seats> node
				if(node.getNodeType() == Node.ELEMENT_NODE
						&& "seats".equals(node.getNodeName())) {
					seatsNode = node;
					break;
				}
			}
		}
		if(seatsNode != null) {
			String seatsString = seatsNode.getTextContent();
			try {
				int seats = Integer.parseInt(seatsString);
				sum += seats;
			} catch (NumberFormatException e) {
				// Incorrect number format is silently ignored (sum is not increased).
			}
		}
	}
}
