<%@ page import="java.util.*" %>

<%@ page errorPage="error.jsp" %>

<jsp:useBean id="customer" class="hansen.playground.Customer" scope="session" />

<%@ include file = "util.inc" %> <!-- contains "cString" -->

<%

String url = request.getRequestURI(); // name of this file

// get command
String command = cString(request.getParameter("command"));

if (command.equals("prompt")) {
// prompt user for the id
session.putValue("customerinfo.message","");
} else if (command.equals("getdata")) {
// let the bean fetch data for this customer
String id = cString(request.getParameter("id"));
customer.setId(id);
if (customer.readCustomerInfo() == 1) {
// id found
session.putValue("customerinfo.message","Customer found");
} else {
session.putValue("customerinfo.message","Customer not found");
}
} else if (command.equals("update")) {
// Update is only valid if the ID in the form matches the ID of the current customer 
String fid = cString(request.getParameter("id"));
if (!customer.isDataFound() || !(customer.getId()).equals(fid)) {
session.putValue("customerinfo.message","Please search customer data first");
} else { 
// Update is allowed--get new name and address from form
String name = cString(request.getParameter("name"));
String address = cString(request.getParameter("address"));
// Do the update through the bean 
customer.setName(name);
customer.setAddress(address);
if (customer.updateCustomer() == 1) {
session.putValue("customerinfo.message","Data successfully updated");
} else {
session.putValue("customerinfo.message","Systemerror - Data was not updated");
}

} else if (command.equals("delete")) {
// Update is only valid if the ID in the form matches the ID of the current customer 
String fid = cString(request.getParameter("id"));
if (!customer.isDataFound() || !(customer.getId()).equals(fid)) {
session.putValue("customerinfo.message","Please search customer data first");
} else { 
// Delete is allowed
if (customer.deleteCustomer() == 1) {
session.putValue("customerinfo.message","Customer successfully deleted");
} else {
session.putValue("customerinfo.message","Systemerror - Customer was not deleted");
}

} else if (command.equals("create")) {
String nid = cString(request.getParameter("id"));
customer.setId(nid);
if (customer.readCustomerInfo() == 1) {
session.putValue("customerinfo.message","Customer ID already used");
} else { 
// ID not used yet
String name = cString(request.getParameter("name"));
String address = cString(request.getParameter("address"));
// Do the create through the bean 
customer.setName(name);
customer.setAddress(address);
if (customer.createCustomer() == 1) {
session.putValue("customerinfo.message","Customer successfully created");
} else {
session.putValue("customerinfo.message","Systemerror - Customer was not created");
}
}
} else if (command.equals("")) throw new Exception("No command given to "+url);
else throw new Exception("Invalid command (" + command + ") given to "+url);

pageContext.forward("customerinfo.jsp");

%>