package com.etixpert.evolution.gui.servlets.pageactions;

import javax.servlet.http.*;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;

import com.etixpert.evolution.gui.servlets.*;
import com.etixpert.evolution.*;

import java.util.*;
import java.math.*;


/**
 * @author Peter Albert
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class orderadd extends PageActionHandler {
    	String error;
    	String details;
    	String currentID;
    	protected String toNewPos;
    /**
     * 
     */
    public orderadd() {
        super();
        error = "order_error";
        details = "order_details";
        currentID = "CURRENT_ORDER_ID";
        toNewPos = "to_det_pos";
        // 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 {
         HttpSession session = request.getSession();
		 String id = request.getParameter("art_id");
         PersistableObject po = new PersistableObject("currentarticles","id");
         try {
             po.set("id",id);
             po.load();
         } catch(Exception e) {
             session.setAttribute(error,LocaleSupport.getLocalizedMessage(pageContext, "NO_ARTICLE"));
             return;
         }
         //Map myMap = FormHelper.getArticle(id, MainControl.logger);
         
         boolean firstorder = false;
         if (session.getAttribute("modify_fo")!=null)
        	 firstorder = true;
         
         String descr = (String) po.get("descr");
         String country_code = request.getParameter("orderingCountry");
         
		 String uid = request.getParameter("UID");
		 //boolean noVat = uid!=null && uid.length()>0 && "DE".equals(country_code);
		 
         
         PersistableObject po_country = new PersistableObject("country", "country_code");
         po_country.set("country_code", country_code);
         po_country.load();
        
         String tax_id = po_country.getString("tax_id", "");
         
         boolean noVat = uid!=null && uid.length()>0 && !"".equals(tax_id) && !"0".equals(tax_id) //&& "DE".equals(country_code);
         && !"AT".equals(country_code);
         
         int level = 100;
         String levelStr = request.getParameter("orderingLevelId");
		 String drStr = request.getParameter("orderingDiscountRate");
         
         try {
         	level = Integer.parseInt(levelStr);
         } catch (Exception e) {
         	level = 100;
         }
         
		 boolean dealer = false;
		 float dr = 0;
//		 if (level==80) {
//			 dealer = true;
//			 try {
//				 dr = new Float(drStr).floatValue();
//			 } catch (Exception e) {
//				 throw new Exception("Discount rate is invalid : "+drStr);
//			 }
//		 }         
         
         Double netto = (Double) po.get("netto");
         Double bonus = (Double) po.get("bonus");
         Double points = (Double) po.get("points");
         String vatClass = po.getString("vat_id", "1");
         
         if (vatClass.equals("0")) vatClass="1";
         
		 Double netto_customer = (Double) po.get("netto_customer");
		 Double netto_silver_customer = (Double) po.get("netto_silver_customer");
		 Double netto_gold_customer = (Double) po.get("netto_gold_customer");
		 Double netto_vip_customer = (Double) po.get("netto_vip_customer");
		 Double netto_handler = (Double) po.get("netto_handler");
		 Double netto_grosshandler = (Double) po.get("netto_grosshandler");

		 
         BigDecimal vat = (BigDecimal) po_country.get("vat"+vatClass);
         if (noVat) vat = new BigDecimal(0);
         BigDecimal brutto = new BigDecimal(0);
         
         //int level= Integer.valueOf(OrderHelper.getVal(m, "orderingLevel")).intValue();
         double d_points = points!=null?points.doubleValue():0;
		 double d_bonus = bonus.doubleValue();
                  
         double d_nettoDist = netto.doubleValue(); 
		 double d_nettoCustomer = netto_customer.doubleValue();
		 double d_nettoSilverCustomer = netto_silver_customer.doubleValue();
		 double d_nettoGoldCustomer = netto_gold_customer.doubleValue();
		 double d_nettoVipCustomer = netto_vip_customer.doubleValue();
		 double d_nettoHandler = netto_handler.doubleValue();
		 double d_nettoGrossHandler = netto_grosshandler.doubleValue();
		 
         double d_netto = 0;
         
		 double tradeMargin = 0;
		 boolean handler = false;
		 boolean grosshandler = false;
		 if (level == 100) {
			 d_netto = d_nettoCustomer;
			 tradeMargin = (d_bonus * 25) / 100;
		 }
		 else if (level == 130) {
			 d_netto = d_nettoSilverCustomer;
			 tradeMargin = (d_bonus * 15) / 100;
		 }
		 else if (level == 160) {
			 d_netto = d_nettoGoldCustomer;
			 tradeMargin = (d_bonus * 10) / 100;
		 }
		 else if (level == 200) {
			 d_netto = d_nettoVipCustomer;
			 tradeMargin = (d_bonus * 5) / 100;
		 }
		 else if (level == 300) {
			 handler = true;
			 if (!firstorder)
				 d_netto = d_nettoHandler;
			 else
				 d_netto = d_nettoGrossHandler;
		 }
		 else if (level == 330 || level == 370) {
			 grosshandler = true;
			 d_netto = d_nettoGrossHandler;
		 }
		 else if (level == 350) {
			 grosshandler = true;
			 d_netto = d_nettoGrossHandler;
		 }
		 else d_netto = d_nettoDist;

         //double tradeMargin = d_netto - d_nettoDist;  

		 if (dealer) {
			 //if (d_bonus !=0)
				// d_netto = d_bonus * (100 - dr) / 100;
//			 d_netto = d_netto * (100 - dr) / 100;
		 }

         
		 double d_brutto = d_netto + (d_netto * vat.doubleValue())*.01;	         
		 java.text.NumberFormat nf = java.text.NumberFormat.getInstance(Locale.ENGLISH);
		 nf.setMinimumFractionDigits(2);
		 nf.setMaximumFractionDigits(2);
		 nf.setGroupingUsed(false);
	
		 Map orders = (Map)session.getAttribute(details);
		 int count = 0;
		 if (orders.get("count")!=null)
		 	count = ((Integer)orders.get("count")).intValue(); 	
	
  		 Map newRow = new HashMap();
  		 
		 if (dealer) {
			 d_points = 0;
			 d_bonus = 0;
		 }  		 
  		 
  		newRow.put("netto", new String[] {nf.format(d_netto)});
  		
  		if (handler || grosshandler)
  			newRow.put("list", new String[] {nf.format(d_netto)});
  		else
  			newRow.put("list", new String[] {nf.format(d_nettoDist)});
  		
		newRow.put("brutto", new String[] {nf.format(d_brutto)});
		newRow.put("points", new String[] {nf.format(d_points)});
		newRow.put("bonus", new String[] {nf.format(d_bonus)});
		newRow.put("trade_margin", new String[] {nf.format(tradeMargin)});
		newRow.put("art_id", new String[] {id});
		newRow.put("art_name", new String[] {descr});
		newRow.put("art_position", new String[] {String.valueOf(count)});
		newRow.put("comment", new String[] {""});
		newRow.put("order_id", new String[] {(String)session.getAttribute(currentID)});
		newRow.put("quantity", new String[] {String.valueOf("1")});
		newRow.put("vat_value", new String[] {nf.format(vat)});
		if (details.indexOf("abo")!=-1)
			newRow.put("subscription", new String[] {"yes"});
	
		orders.put(String.valueOf(count), newRow);
		
		orders.put("count", new Integer(count+1));
		session.setAttribute(toNewPos, "quantity"+String.valueOf(count));
      }
    
    
    		

}
