package xml.rooms;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import xml.pomoce.Args;

public class CountSeats_XPath_ZPliku {
	public static void main(String[] args) {
		args = Args.argsOrDefault(args, "rooms.xml");
		String input = args[0];
		try {
			CountSeats_XPath_ZPliku program = new CountSeats_XPath_ZPliku();
			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, XPathExpressionException {
		System.out.println("Starting with file " + fileName);
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = dbf.newDocumentBuilder();
		Document doc = builder.parse(fileName);
		
		Source src = new DOMSource(doc);
		
		XPathFactory xpf = XPathFactory.newInstance();
		XPath xpath = xpf.newXPath();
		
		Double wynik = (Double)xpath.evaluate("sum(/rooms/room[equipment/@projector='true']/seats)", src, XPathConstants.NUMBER);
		
		return wynik.intValue();
	}
}

