package xml;

import futils.Futil;
import net.Cart;


import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;

import org.xml.sax.SAXParseException;
import org.xml.sax.SAXException;

public class Xml2Cart {

  public static void main(String argv [])
      throws IOException {
    try {

      getCart();

    } catch (SAXParseException e) {
      System.out.println(
          "** Parsing error"
          + ", line " + e.getLineNumber()
          + ", uri " + e.getSystemId()
          + "   " + e.getMessage()
      );

    } catch (SAXException e) {
      e.printStackTrace();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    }
  }

  private static void getCart()
      throws SAXParseException, SAXException,
      ParserConfigurationException, IOException {
    Cart c = read("file:" +
                  Futil.getReadFile(
                      "select an XML file").getAbsolutePath());
    System.out.println("Cart=" + c);
  }

  public static Cart read(String uri)
      throws SAXParseException,
      SAXException,
      ParserConfigurationException,
      IOException {
    SAXParserFactory spf =
        SAXParserFactory.newInstance();
    spf.setValidating(true);
    SAXParser sp = spf.newSAXParser();

    CartDocumentHandler dh = new CartDocumentHandler();
    sp.parse(uri,dh);
    return dh.getCart();
  }
}