<%-- 
    Document   : createInvoice
    Created on : Apr 15, 2009, 7:33:26 PM
    Author     : sg128468
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.text.*,
                java.util.*,
                org.w3c.dom.*,
                org.odftoolkit.odfdom.dom.OdfNamespace,
                org.odftoolkit.odfdom.dom.type.OdfPositiveInteger,
                org.odftoolkit.odfdom.doc.OdfDocument,
                org.odftoolkit.odfdom.doc.OdfFileDom,
                org.odftoolkit.odfdom.doc.element.text.*,
                org.odftoolkit.odfdom.doc.element.office.*,
                org.odftoolkit.odfdom.doc.element.table.*,
                javax.xml.xpath.*" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Customer Invoice generated.</h1>
        <%
		// Edit the lab root - it's the base directory for reading the input file
		// and for writing the result
		LAB_ROOT = <LAB_ROOT>";
        // Read received post parameter
        String name = request.getParameter("myName");
        String street = request.getParameter("myStreet");
        String zip = request.getParameter("myZip");
        String city = request.getParameter("myCity");
        String[] productIds = request.getParameterValues("myProdID");
        String[] productNames = request.getParameterValues("myProdName");
        String[] productQuantities = request.getParameterValues("myProdQuantity");
        String[] productPrices = request.getParameterValues("myProdPrice");
          ////////////////////////////////////////////////////////////////
          // Start ODFDOM handling
          ////////////////////////////////////////////////////////////////
          // 1. Load invoice template 
          OdfDocument document = OdfDocument.loadDocument(LAB_ROOT + "/resources/invoice_template.odt");
          // 1.1 Get the Content DOM of this Text Document
          OdfFileDom content = document.getContentDom();
          ////////////////////////////////////////////////////////////////
          // 2. Create OdfSpan elements for curstomer address and current date
          // 2.1 Add Name
          OdfSpan spanName = new OdfSpan(content);
          spanName.setTextContent(name);
          // 2.2 Street
          OdfSpan spanStreet = new OdfSpan(content);
          spanStreet.setTextContent(street);
          // 2.2 Zip And City
          OdfSpan spanCity = new OdfSpan(content);
          spanCity.setTextContent(zip + " " + city);
          // 2.3 Current Date
          OdfSpan spanDate = new OdfSpan(content);
          SimpleDateFormat dateFormater = new SimpleDateFormat();
          String dateStr = dateFormater.getDateInstance(DateFormat.FULL).format(new Date());
          spanDate.setTextContent(dateStr);
          ////////////////////////////////////////////////////////////////
          // 3. Find all placeholder elements
          XPath xpath = XPathFactory.newInstance().newXPath();
          xpath.setNamespaceContext(new OdfNamespace());
          NodeList placeholder = (NodeList)xpath.evaluate("//text:placeholder", content, XPathConstants.NODESET);
          // 3.1 Apply Address Details and Date
          for(int i=0; i<placeholder.getLength(); i++) {
              OdfPlaceholder pl = (OdfPlaceholder)placeholder.item(i);
              OdfParagraph parentParagraph = (OdfParagraph)pl.getParentNode();
              String placeholderText = pl.getTextContent();
              if(placeholderText.indexOf("_NAME_") > 0) {
                  parentParagraph.replaceChild(spanName, pl);
              } else if(placeholderText.indexOf("_STREET_") > 0) {
                  parentParagraph.replaceChild(spanStreet, pl);
              } else if(placeholderText.indexOf("_ZIPCITY_") > 0) {
                  parentParagraph.replaceChild(spanCity, pl);
              } else if(placeholderText.indexOf("_CURRENTDATE_") > 0) {
                  parentParagraph.replaceChild(spanDate, pl);
              }
          }
          ///////////////////////////////////////////////////////
          // 4. Calculate Product Details and add them as Table Rows
          // 4.1 Find the Billing Table
          xpath = XPathFactory.newInstance().newXPath();
          xpath.setNamespaceContext(new OdfNamespace());
          OdfTable table = (OdfTable)xpath.evaluate("//table:table[1]", content, XPathConstants.NODE);
          // 4.2 Find the first Row get the style info for table cell
          OdfTableRow firstRow = (OdfTableRow)table.getElementsByTagName("table:table-row").item(0);
          // 4.3 Calculate row sum to insert
          float priceOverall = 0;
          // 4.4 Insert rows for billing items
          for(int i=0; i < productIds.length; i++) {
              OdfTableRow billingItemRow = new OdfTableRow(content);
              // 4.4.1 Add cells billing item details
              for(int j=0; j < 5; j++) {
                  // Create new Cell
                  OdfTableCell cell = new OdfTableCell(content);
                  // Get and set correct style name for this cell
                  cell.setStyleName( ((OdfTableCell)firstRow.getCellAt(j)).getStyleName() );
                  // Create new Paragraph
                  OdfParagraph paragraph = new OdfParagraph(content);
                  // Set correct style name for this cell
                  paragraph.setStyleName( "Table_20_Contents" );
                  // Apply text regarding the current cell index
                  if(j == 0) {
                      paragraph.setTextContent(productIds[i]);
                  } else if(j == 1) {
                      paragraph.setTextContent(productNames[i]);
                  } else if(j == 2) {
                      paragraph.setTextContent(productQuantities[i]);
                  } else if(j == 3) {
                      paragraph.setTextContent(productPrices[i]);
                  } else if(j == 4) {
                      float priceTotal = Float.parseFloat(productPrices[i])*Float.parseFloat(productQuantities[i]);
                      priceOverall += priceTotal;
                      paragraph.setTextContent(String.valueOf(priceTotal));
                  }
                  cell.appendChild(paragraph);
                  billingItemRow.appendCell(cell);
              }
              table.appendRow(billingItemRow);
          }
          // 4.5 Add last row showing overall price
          OdfTableRow lastRow = new OdfTableRow(content);
          OdfTableCell cell = new OdfTableCell(content);
          cell.setNumberColumnsSpanned(OdfPositiveInteger.valueOf("4"));
          lastRow.appendCell(cell);
          cell = new OdfTableCell(content);
          OdfParagraph paragraphFullPrice = new OdfParagraph(content);
          paragraphFullPrice.setStyleName("SumPrice");
          paragraphFullPrice.setTextContent(String.valueOf(priceOverall));
          cell.appendChild(paragraphFullPrice);
          lastRow.appendCell(cell);
          table.appendRow(lastRow);
          ///////////////////////////////////////////////////////
          // 5. Save the resulting file
          // Save to a place of your choice
          document.save(LAB_ROOT + "/solutions/solution2/output_1_generated_invoice.odt");

        %>
    </body>
</html>
