/*
 * 
 * Created on May 31, 2005
 * 
 * Gy�rgy S�veges
 * Etixpert Kft.
 * Copyright(c) 2005
 * 
 */
package com.etixpert.evolution.gui.servlets.pageactions;

import javax.servlet.http.*;

import com.etixpert.evolution.gui.servlets.*;
import com.etixpert.evolution.*;
import org.hibernate.*;
import java.util.*;
import java.math.*;



/**
 * @author Suveges Gyorgy
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class ordermake extends PageActionHandler {

    /**
     * 
     */
    public ordermake() {
        super();
        // TODO Auto-generated constructor stub
    }

    /* (non-Javadoc)
     * @see com.etixpert.evolution.gui.servlets.pageactions.PageActionHandler#handle(javax.servlet.http.HttpServletRequest)
     */
    protected void handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map m = (Map) request.getSession().getAttribute("new_order.jsp");
        PersistableObject orderHeader = new PersistableObject("order_header","id");
        
        
        logger.info("Collecting data to store from session");
        String payMethodStr=OrderHelper.getVal(m, "Zahlungsart","4");
        if (payMethodStr.equals("")) payMethodStr="4";
        Integer payMethodId = Integer.valueOf(payMethodStr);
        java.sql.Date now = new java.sql.Date(System.currentTimeMillis());
        orderHeader.set("order_date", now);
        if (payMethodId.intValue()!=4 && payMethodId.intValue()!=3)
            orderHeader.set("bonus_date", now);
        
        if (payMethodId.intValue()==1) {
            orderHeader.set("account_id", Integer.valueOf(OrderHelper.getVal(m,"bank")));
        } else if (payMethodId.intValue()==2)
            orderHeader.set("account_id", Integer.valueOf(OrderHelper.getVal(m, "credit")));
        
        String tradeMargin = OrderHelper.getVal(m,"trade1","0");
        orderHeader.set("trade_margin", new BigDecimal(tradeMargin));
        orderHeader.set("store_descr","Villach");
        orderHeader.set("order_status_id", new Integer(10));
        orderHeader.set("order_type", new Integer(3));
        
        PersistableObject payMethod = new PersistableObject("payment_method","id");
        payMethod.set("id", payMethodId);
        payMethod.load();
        String payMethodDescr = payMethod.getString("descr","");
        orderHeader.set("pay_method_id", payMethodId);
        orderHeader.set("pay_method_descr", payMethodDescr);
        orderHeader.set("shipping_descr", OrderHelper.getVal(m, "shipping","1"));
        orderHeader.set("comment", OrderHelper.getVal(m, "comment",""));
        String[] deliveryName = getTitleAndName(OrderHelper.getVal(m,"delivery"));
        orderHeader.set("delivery_title", deliveryName[0]);
        orderHeader.set("delivery_name", deliveryName[1]);
        
        String deliveryIdStr = OrderHelper.getVal(m, "deliveryaddresses","");
        if (!deliveryIdStr.equals("")) {
	        Integer deliveryId = Integer.valueOf(deliveryIdStr);
	        PersistableObject address = new PersistableObject("address", "id");
	        address.set("id", deliveryId);
	        address.load();
	        orderHeader.set("delivery_country_id", address.get("country_post_code"));
	        orderHeader.set("delivery_postcode", address.get("postcode"));
	        orderHeader.set("delivery_city", address.get("city"));
	        orderHeader.set("delivery_street", address.get("street"));
        }
        String billIdStr = OrderHelper.getVal(m, "billaddresses","");
        if (!billIdStr.equals("")) {
	        Integer billId = Integer.valueOf(billIdStr);
	        PersistableObject address = new PersistableObject("address", "id");
	        address.set("id", billId);
	        address.load();
	        orderHeader.set("billing_country_id", address.get("country_post_code"));
	        orderHeader.set("billing_postcode", address.get("postcode"));
	        orderHeader.set("billing_city", address.get("city"));
	        orderHeader.set("billing_street", address.get("street"));
        }
        Integer orderedBy = Integer.valueOf(OrderHelper.getVal(m, "cnr"));
        orderHeader.set("ordered_by", orderedBy);
        logger.info("Data collected, trying to save order header");
        orderHeader.insert();
        logger.info("order_header saved successfully");
        
        String poses = OrderHelper.getVal(m,"positions","");
        String [] positions = poses.split(";");
        ObjectSearch os = new ObjectSearch();
        List l = os.search("select {fn currval('seq_order_header')}");
        PersistableObject currvalRow = (PersistableObject) l.get(0);
        logger.info(currvalRow.get("currval").getClass());
        Long  currval = (Long) currvalRow.get("currval");
        
        for (int i=1; i<=positions.length; i++) 
            addOrderDetail(m,currval, i, positions[i-1]);
        
        logger.info("currval: "+currval);
        
        HttpSession session = request.getSession();
        session.removeAttribute("new_order_person_select.jsp");
        session.removeAttribute("new_order.jsp");
        OrderHelper.setMessage(request, "Bestellung wurde erfolgreich durchgeführt");
        
        
    }
    
    protected void addOrderDetail(Map m, Long orderID, int artpos, String pos) throws Exception {
        logger.info("inserting order entry for orderid "+orderID.longValue()+" and for "+artpos);
        PersistableObject orderDetail = new PersistableObject("order_detail","id");
        orderDetail.set("art_name", OrderHelper.getVal(m, "descr"+pos));
        orderDetail.set("art_position", new Integer(artpos));
        orderDetail.set("quantity", Integer.valueOf(OrderHelper.getVal(m, "quant"+pos)));
        orderDetail.set("bonus", new BigDecimal(OrderHelper.getVal(m,"bonus"+pos)));
        orderDetail.set("netto", new BigDecimal(OrderHelper.getVal(m, "netto"+pos)));
        orderDetail.set("points", new BigDecimal(OrderHelper.getVal(m, "points"+pos)));
        orderDetail.set("vat_value", new BigDecimal(OrderHelper.getVal(m, "vat"+pos)));
        orderDetail.set("art_id", OrderHelper.getVal(m, "id"+pos));
        orderDetail.set("order_id", orderID);
        logger.info("order entry for orderid "+orderID.longValue()+" and for "+artpos+" inserted");
        orderDetail.insert();
    }
    
    protected String[] getTitleAndName(String name) {
        String[] split = new String[2];
        
        if (name.startsWith("Frau ") || name.startsWith("Herr ")) {
            split[0]= name.substring(0,4);
            split[1]=name.substring(5);
            return split;
        } else {
            split[0]="";
            split[1]=name;
            return split;
        }
    }

}
