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

import java.io.OutputStream;
import java.sql.*;
import java.util.*;
import java.text.*;
import com.etixpert.evolution.*;
import javax.servlet.http.*;

import com.etixpert.evolution.app.order.*;
import java.io.*;
import org.apache.log4j.*;
/**
 * @author Suveges Gyorgy
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class OrderListHelper {
    private static SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
    /**
     * 
     */
    
    public static String rightToNextStatus(Connection conn, PersistableObject person, int from) throws SQLException, EvolutionException {
       PersistableObject orderStatusRight = new PersistableObject("order_status_rights", new String[]{"role_id", "order_status_id"});
       orderStatusRight.set("role_id", person.get("level_id"));
       orderStatusRight.set("order_status_id", new Integer(from));
       orderStatusRight.load(conn);
       return orderStatusRight.getString("nextproc","");
       
     }
    
     
    public static String nextProcess(Connection conn, int from) throws SQLException, EvolutionException {
       
        PersistableObject orderStatus = new PersistableObject("order_status", "id");
        orderStatus.set("id", new Integer(from));
        orderStatus.load(conn);
        return orderStatus.getString("next_process","");
    }
    
    public static boolean showChangeBonusDate(Connection conn, PersistableObject generalRights, PersistableObject orderStatus) throws SQLException {
    	
    	
    	Boolean changeBonusDateAvailable = (Boolean) orderStatus.get("change_bonus_date");
    	if (changeBonusDateAvailable==null || !changeBonusDateAvailable.booleanValue())
    		return false;
    	
    	Calendar cal = Calendar.getInstance();
    	int day = cal.get(Calendar.DAY_OF_MONTH);
    	if (day >5)
    		return false;
    	
    	ObjectSearch os = new ObjectSearch();
    	List l = os.search(conn, "select max(id) as last_bonus_calculation from bonus_history");
    	if (l.size()>0) {
    		PersistableObject po = (PersistableObject)l.get(0);
    		java.sql.Date lastBonusCalculation= (java.sql.Date) po.get("last_bonus_calculation");
    		if (lastBonusCalculation!=null) {
    				Calendar lastBonusCalc = Calendar.getInstance();
    				lastBonusCalc.setTime(lastBonusCalculation);
    				
    				if (cal.after(lastBonusCalculation) && 
    						cal.get(Calendar.MONTH)==lastBonusCalc.get(Calendar.MONTH) &&
    						cal.get(Calendar.YEAR)==lastBonusCalc.get(Calendar.YEAR))
    							return false;
    			
    		
    		}
    	}
    	
    	String rightToChangeBonusDate = generalRights.getString("change_bonus_date","x");
    	boolean canChangeBonusDate = rightToChangeBonusDate.equalsIgnoreCase("x") || rightToChangeBonusDate.equals("")?false:true;
    	return canChangeBonusDate;
    	
    }
    
    public static Integer nextOrderStatus(Connection conn, int from) throws SQLException, EvolutionException {
        if (from==60) return null;
        ObjectSearch os =new ObjectSearch();
        List l = os.search(conn, "select min(id) as next_id from order_status where id> ?", new Object[]{new Integer(from)});
        PersistableObject res = (PersistableObject) l.get(0);
        return (Integer) res.get("next_id");
    }
    
    public static void downloadBill(HttpServletRequest req, HttpServletResponse res) throws IOException{
        String order_id = req.getParameter("id");
        Long l = Long.valueOf(order_id);
        Logger logger = Logger.getLogger("mainControl.OrderListHelper");
        String realPath = req.getSession().getServletContext().getRealPath("/WEB-INF/");
        logger.info("Realpath of web-inf is: "+realPath);
        byte[] data = Bill.generate(l, realPath);
        res.setContentType("application/octet-stream");
		res.setHeader("Content-Disposition","attachment; filename="+l+".pdf"); 
		
		logger.info(data==null?"data is null!!!!!!":"Data length: "+data.length);
		
		OutputStream os = res.getOutputStream();
		os.write(data);
    }
    
	public static void printAddresses(String[] orderIds, HttpServletRequest req, HttpServletResponse res) throws Exception {
		String realPath = req.getSession().getServletContext().getRealPath("/WEB-INF/");
		if (orderIds == null) orderIds = new String[0];
		byte[] data = Bill.generate2(orderIds, realPath);
		res.setContentType("application/octet-stream");
		res.setHeader("Content-Disposition","attachment; filename=adressen.pdf"); 
		OutputStream os = res.getOutputStream();
		os.write(data);
	}    
    
    public static String getBillLink(PersistableObject po) throws Exception {
        Long id = (Long) po.get("order_id");
        Long bill_id = (Long) po.get("bill_id");
        if (bill_id == null) return "-";
        String link = "<a href=\"process/download_bill?pageAction=download_bill&id=" + id + "&saveState=nothing\">"+bill_id+"</a>";
        return link;
        
    }
    
    public static List search(Connection conn, String right, Integer uid,
			String nameOrId, String[] countryCodes, String[] paymentMethods,
			String orderId, String billId, String status, String payed,
			String from, String to, String rfrom, String rto, String bfrom, String bto, String old, String orderBy) throws Exception {
    	return search(conn, right, uid, nameOrId, countryCodes, paymentMethods, orderId, billId, status, payed, from, to, rfrom, rto, bfrom, bto, old, orderBy, "", "");
    }
    
    
    public static List search(Connection conn, String right, Integer uid,
            					String nameOrId, String[] countryCodes, String[] paymentMethods,
            					String orderId, String billId, String status, String payed,
            					String from, String to, String rfrom, String rto, String bfrom, String bto, String old, String orderBy, String creditNotes, String customerDiscount) throws Exception {
        
        
        ArrayList where = new ArrayList();
        ArrayList params = new ArrayList();
        params.add(uid);
        Integer did = null;
        if (!nameOrId.equals("")) {
	        try {
	            did = Integer.valueOf(nameOrId);
	        } catch (Exception e) {
	            ;
	        }
	        
	        if (did == null) {
	            where.add("(lower(lastname) like ?)");
	            params.add(nameOrId.toLowerCase()+"%");

	        }
	        else {
	            where.add("((lower(lastname) like ?) or (d.id::text like ?))");
	            params.add(nameOrId.toLowerCase()+"%");
	            params.add("%"+nameOrId+"%");
	        }
        }
        
        if (countryCodes!=null) {
            addCondition("country_code",countryCodes, where, params, false);
            
        }
        
       
        if (paymentMethods!=null) {
            addCondition("o.pay_method_id", paymentMethods, where, params, true);
        }
        
        if (!orderId.equals("")) {
         where.add("(o.id::text like ?)");
         params.add("%"+orderId+"%");
        }
        
        if (!billId.equals("")) {
            where.add("(o.bill_id::text like ?)");
            params.add("%"+billId+"%");
        }
        
        if (!status.equals("")) {
            where.add("(order_status_id = ?)");
            params.add(Integer.valueOf(status));
            	
        }
        
        if (!from.equals("")) {
            where.add("(order_date >= ?)");
            params.add(new java.sql.Date(sdf.parse(from).getTime()));
        }
        
        if (!to.equals("")) {
            where.add("(order_date <= ?)");
            params.add(new java.sql.Date(sdf.parse(to).getTime()));
        }
       
        if (!"".equals(rfrom)) {
            where.add("(billing_date >= ?)");
            params.add(new java.sql.Date(sdf.parse(rfrom).getTime()));
        }
        
        if (!"".equals(rto)) {
            where.add("(billing_date <= ?)");
            params.add(new java.sql.Date(sdf.parse(rto).getTime()));
        }

        if (!"".equals(bfrom)) {
            where.add("(bonus_date >= ?)");
            params.add(new java.sql.Date(sdf.parse(bfrom).getTime()));
        }
        
        if (!"".equals(bto)) {
            where.add("(bonus_date <= ?)");
            params.add(new java.sql.Date(sdf.parse(bto).getTime()));
        }

        
        if (!status.equals("")) {
            where.add("(order_status_id = ?)");
            params.add(Integer.valueOf(status));
        }
        
        if (!payed.equals("")) {
            where.add("(payment_status = ?)");
            params.add(new Boolean(payed));
        }
        
        if (!"".equals(creditNotes)) {
           	where.add("(total_brutto < 0 or total_brutto_trader < 0)");
        }
        
        if (!"".equals(customerDiscount)) {
           	where.add("(orderer_level_id >= 100 and orderer_level_id <= 200 and o.discount_rate > 0)");
        }
        
        
        if (!old.equals("")) {
            where.add("(d.id>=43000000 AND d.id<44000000 AND d.old_distr)");
        }
        
        ObjectSearch os = new ObjectSearch();
        String query = "select o.id as order_id, d.active as active, o.order_status_id, ot.descr as order_type, order_date,bonus_date, payment_status, pay_method_descr, bill_id, d.country_code, d.id,  d.company, d.lastname, d.firstname, "+
        			"o.total_netto, o.total_netto_trader, o.total_bonus, o.total_points, o.total_brutto, o.total_brutto_trader, o.orderer_level_id, o.comment, o.discount_rate from order_header o, distributor d, order_type ot, (select "+right+" as id from "+right+"(?)) stuff " +
        			"where ordered_by = d.id and d.id=stuff.id and o.order_type=ot.id" +link(where) + " order by "+orderBy;
        if (orderBy.equalsIgnoreCase("order_date")) query+=" DESC";
        
        Logger logger = Logger.getLogger("mainControl.OrderListHelper");
        logger.info("Searching for orders: "+query);
        
        List l = os.search(conn, query, params.toArray());
        return l;
        
        
        
    }
    public static String[] getVal(Map m, String key) {
        if (m==null) return null;
        return (String[]) m.get(key);
    }
    
    private static void addCondition(String field, String[] values, ArrayList where, ArrayList  params, boolean _int) {
        if (values == null || values.length==0) return;
        String condition = "(" +field+" in (";
        for (int i=0; i<values.length; i++) {
            condition+="?";
            if (_int)
                params.add(Integer.valueOf(values[i]));
            else
                params.add(values[i]);
            if (i<values.length-1) condition+=", ";
        }
        condition+="))";
        where.add(condition);
            
    }
    
 
    private static String link(List where) {
        StringBuffer sb = new StringBuffer();
        
        for (int i=0; i<where.size(); i++) {
            sb.append(" AND ");
            sb.append((String) where.get(i));
            
        }
        
        return sb.toString();
            
            	
    }
    
    
    public static String getBonusDateField(PersistableObject o, boolean enableChange) throws Exception {
        
    	java.sql.Date bd = (java.sql.Date) o.get("bonus_date");
        if (bd==null) return "-";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
         
        if (!enableChange) 
        	return sdf.format(bd);
        	
        
        
        Calendar bonusDate = Calendar.getInstance();
        bonusDate.setTime(bd);
        Calendar now = Calendar.getInstance();
        
        if (now.get(Calendar.YEAR) == bonusDate.get(Calendar.YEAR) && 
        	now.get(Calendar.MONTH) == bonusDate.get(Calendar.MONTH)) {
        	
        	Calendar prev = (Calendar) bonusDate.clone();
        	prev.set(Calendar.DAY_OF_MONTH, 1);
        	prev.add(Calendar.DAY_OF_MONTH, -1);
        
        	SimpleDateFormat sdfValue = new SimpleDateFormat("yyyy-MM-dd");
        	
        	StringBuffer sb = new StringBuffer();
        	sb.append("<select name=\"bonus_date\">\n");
        	sb.append("<option value=\"").append(o.get("order_id")).append(":").append(sdfValue.format(bd)).append("\" selected=\"selected\">");
        	sb.append(sdf.format(bd)).append("</option>\n");
        	sb.append("<option value=\"").append(o.get("order_id")).append(":").append(sdfValue.format(prev.getTime())).append("\">");
        	sb.append(sdf.format(prev.getTime())).append("</option>\n");
        	sb.append("</select>");
        	return sb.toString();
        	
        }  else 
        	return sdf.format(bd);
    }
    
    public static String dateToString(java.sql.Date date) throws Exception {
        if (date == null) return "-";
        return sdf.format(date);
 
    }
    
    public static String numberToString(Object o, int fractionDigits) throws Exception {
        if (o==null) return "-";
        NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
       /* double d=0;
        if (o instanceof BigDecimal) {
            d = ((BigDecimal) o).doubleValue();
        } else if (o instanceof Double) {
            d= ((Double )o).doubleValue();
        } else if (o instanceof Float) {
            d = ((Float) o).doubleValue();
        } else if (o instanceof Long) {
            return nf.format(((Long)o).longValue());
        } else if (o instanceof Integer) {
            return nf.format(((Integer)o).longValue());
        }*/
        
        nf.setMinimumFractionDigits(fractionDigits);
        nf.setMaximumFractionDigits(fractionDigits);
        return nf.format(o);
    }
}
