package com.etixpert.evolution.gui.servlets;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.etixpert.evolution.ObjectSearch;
import com.etixpert.evolution.PersistableObject;

public class DiscountHelper {

	public static final int LEVEL_TYPE_GROSSHANDLER = 1;
	public static final int LEVEL_TYPE_HANDLER = 2;
	public static final int LEVEL_TYPE_CUSTOMER = 3;
	public static final int LEVEL_TYPE_BERATER = 4;
	public static final int LEVEL_TYPE_THERAPEUT = 5;
	public static final int LEVEL_TYPE_APOTHEKER = 6;
	
	public static List loadDefaultLevels(HttpSession session) throws Exception {
		List ret = new ArrayList();
		ObjectSearch os = new ObjectSearch("default_discount_levels", new String[] {"id"});
		os.setOrderBy(new String[] {"id"});
		List result = os.search();
		
		for (Iterator it = result.iterator(); it.hasNext();) {
			PersistableObject po = (PersistableObject)it.next();
			String levelStr = po.getString("id", "0");
			String borderStr = po.getString("border", "0");
			String percStr = po.getString("percentage", "0");
			
			try {
				Float border = new Float(borderStr);
				Float perc = new Float(percStr);
				Integer level = new Integer(levelStr);
				
				ret.add(new DefaultDiscountLevel(level, border, perc));
			} catch (Exception e) {
				
			}
		}
		
		return ret;
	}

	public static List loadDefaultLevelsForGrossHandler(HttpSession session) throws Exception {
		List ret = new ArrayList();
		ObjectSearch os = new ObjectSearch("default_discount_levels_grosshandler", new String[] {"id"});
		os.setOrderBy(new String[] {"id"});
		List result = os.search();
		
		for (Iterator it = result.iterator(); it.hasNext();) {
			PersistableObject po = (PersistableObject)it.next();
			String levelStr = po.getString("id", "0");
			String borderStr = po.getString("border", "0");
			String percStr = po.getString("percentage", "0");
			
			try {
				Float border = new Float(borderStr);
				Float perc = new Float(percStr);
				Integer level = new Integer(levelStr);
				
				ret.add(new DefaultDiscountLevel(level, border, perc));
			} catch (Exception e) {
				
			}
		}
		
		return ret;
	}
	
	public static List loadDefaultLevelsForCustomer(HttpSession session) throws Exception {
		List ret = new ArrayList();
		ObjectSearch os = new ObjectSearch("default_discount_levels_customer", new String[] {"id"});
		os.setOrderBy(new String[] {"id"});
		List result = os.search();
		
		for (Iterator it = result.iterator(); it.hasNext();) {
			PersistableObject po = (PersistableObject)it.next();
			String levelStr = po.getString("id", "0");
			String borderStr = po.getString("border", "0");
			String percStr = po.getString("percentage", "0");
			
			try {
				Float border = new Float(borderStr);
				Float perc = new Float(percStr);
				Integer level = new Integer(levelStr);
				
				ret.add(new DefaultDiscountLevel(level, border, perc));
			} catch (Exception e) {
				
			}
		}
		
		return ret;
	}	
	
	public static List loadDefaultLevelsForHandler(HttpSession session) throws Exception {
		List ret = new ArrayList();
		try {
			Float border = new Float("0");
			Float perc = new Float("0");
			Integer level = new Integer("1");
			
			ret.add(new DefaultDiscountLevel(level, border, perc));
		} catch (Exception e) {
			
		}
		return ret;
	}
	
	public static String getGrossHandlerDefaultDiscountLevel() throws Exception {
		ObjectSearch os = new ObjectSearch("default_discount_levels_grosshandler", new String[] {"id"});
		os.setOrderBy(new String[] {"id"});
		List result = os.search();
		
		PersistableObject po = (PersistableObject)result.get(0);
		return po.getString("percentage", "20");
	}
	
	public static String getCustomerDefaultDiscountLevel() throws Exception {
		ObjectSearch os = new ObjectSearch("default_discount_levels_customer", new String[] {"id"});
		os.setOrderBy(new String[] {"id"});
		List result = os.search();
		
		PersistableObject po = (PersistableObject)result.get(0);
		return po.getString("percentage", "20");
	}	
	
	public static List loadDistributorDiscountLevels(String distr_id) throws Exception {
		List ret = new ArrayList();
		ObjectSearch os = new ObjectSearch("distributor_discount_levels", new String[] {"distr_id"});
		os.setCondition("distr_id = ?");
		os.setOrderBy(new String[] {"level"});
		List result = os.search(new Object[] {new Long(distr_id)});
		
		for (Iterator it = result.iterator(); it.hasNext();) {
			PersistableObject po = (PersistableObject)it.next();
			String percStr = po.getString("percentage", "0");
			String levelStr = po.getString("level", "0");
			
			try {
				Integer level = new Integer(levelStr);
				Float perc = new Float(percStr);
				
				ret.add(new DistributorDiscountLevel(new Integer(distr_id), level, perc));
				
			} catch (Exception e) {}
		}
		return ret;
	}

	public static float isThereDistributorPercentage(Integer level, List from) {
		if (from == null) return 0;
		for (Iterator it = from.iterator(); it.hasNext(); ) {
			DistributorDiscountLevel ddl = (DistributorDiscountLevel)it.next();
			if (ddl.getLevelId().intValue() == level.intValue()) return ddl.getPercentage().floatValue();
		}
		
		return 0;
	}
	
	public static List getDefaultLevels(HttpSession session) throws Exception {
		if (session.getAttribute("def_discount_levels") == null)
			return loadDefaultLevels(session);
		else return (List)session.getAttribute("def_discount_levels");
	}
	
	public static List getDefaultLevelsForGrossHandler(HttpSession session) throws Exception {
		if (session.getAttribute("def_discount_levels_grosshandler") == null)
			return loadDefaultLevelsForGrossHandler(session);
		else return (List)session.getAttribute("def_discount_levels_grosshandler");
	}
	
	public static List getDefaultLevelsForCustomer(HttpSession session) throws Exception {
		if (session.getAttribute("def_discount_levels_customer") == null)
			return loadDefaultLevelsForCustomer(session);
		else return (List)session.getAttribute("def_discount_levels_customer");
	}
	
	public static List getDefaultLevelsForHandler(HttpSession session) throws Exception {
		if (session.getAttribute("def_discount_levels_handler") == null)
			return loadDefaultLevelsForHandler(session);
		else return (List)session.getAttribute("def_discount_levels_handler");
	}

	public static List getDefaultLevelsForApotheker(HttpSession session) throws Exception {
		if (session.getAttribute("def_discount_levels_apotheker") == null)
			return loadDefaultLevelsForHandler(session);
		else return (List)session.getAttribute("def_discount_levels_apotheker");
	}
	
	public static void deleteLevels(Integer distrId, List levels, HttpSession session) throws Exception {
		ObjectSearch os = new ObjectSearch("distributor_discount_levels", new String[] {"distr_id"});
		os.setCondition("distr_id = ?");
		List result = os.search(new Object[] {distrId});
		
		for (int i = result.size()-1; i>=0; i--) {
			PersistableObject po = (PersistableObject)result.get(i);
			po.delete();
		}
	}
	
	public static void saveNewLevels(Integer distrId, List levels, HttpSession session) throws Exception {
		deleteLevels(distrId, levels, session);
		
		for (int i=0; i<levels.size(); i++) {
			DistributorDiscountLevel ddl = (DistributorDiscountLevel)levels.get(i);
			PersistableObject po = new PersistableObject("distributor_discount_levels", new String[] {"distr_id"});
			po.set("level", ddl.getLevelId());
			po.set("percentage", ddl.getPercentage());
			po.set("distr_id", distrId);
			
			po.insert();
		}		
	}
	
	public static int getLevel(double netto, HttpSession session, int type) throws Exception {
		List defLevels = null;
		
		if (type == LEVEL_TYPE_GROSSHANDLER) 
			defLevels = getDefaultLevelsForGrossHandler(session);
		else if (type == LEVEL_TYPE_HANDLER || type == LEVEL_TYPE_THERAPEUT)
			defLevels = getDefaultLevels(session);
		else if (type == LEVEL_TYPE_CUSTOMER)
			defLevels = getDefaultLevelsForCustomer(session);
		
		
		for (int i = defLevels.size()-1; i>=0; i--) {
			DefaultDiscountLevel ddl = (DefaultDiscountLevel)defLevels.get(i);
			float border = ddl.getBorder().floatValue();
			if (Math.abs(netto) > border) return ddl.getLevelId().intValue();
		}
		return 0;
	}
	
	public static void cacheOrderingDistributorLevels(Integer distrId, HttpSession session, int type, boolean newhandler) throws Exception {
		MainControl.logger.info("KKKKnewhandler: " + newhandler);
		List defLevels = null; 
				
		if (type == LEVEL_TYPE_GROSSHANDLER)
			defLevels = getDefaultLevelsForGrossHandler(session);
		else if (type == LEVEL_TYPE_HANDLER || type == LEVEL_TYPE_THERAPEUT)
			defLevels = newhandler?getDefaultLevelsForHandler(session):getDefaultLevels(session);
		else if (type == LEVEL_TYPE_APOTHEKER)
			defLevels = getDefaultLevelsForApotheker(session);
		else if (type == LEVEL_TYPE_CUSTOMER)
			defLevels = getDefaultLevelsForCustomer(session);
			
		List distLevels = loadDistributorDiscountLevels(distrId.toString());
		Map discount = new HashMap();
		
		discount.put(new Integer(0), new Float(0));
		
		for (int i = 0; i< defLevels.size(); i++) {
			DefaultDiscountLevel ddl = (DefaultDiscountLevel)defLevels.get(i);
			Integer level = ddl.getLevelId();
			Float perc = ddl.getPercentage();
			MainControl.logger.info("KKKKPerc: " + perc);
			float diff = isThereDistributorPercentage(level, distLevels);
			MainControl.logger.info("KKKKDiff: " + diff);
			Float realPerc = new Float(perc.floatValue() + diff);
			MainControl.logger.info("KKKKRealPerc: " + realPerc);
			discount.put(level,  realPerc);
		}
		
		session.setAttribute("CURRENT_HANDLER_DISCOUNT", discount);
		if (type == LEVEL_TYPE_GROSSHANDLER) {
			session.setAttribute("CURRENT_GROSSHANDLER_DISCOUNT", discount.get(new Integer(1)));
		} else if (newhandler) {
			if (type == LEVEL_TYPE_HANDLER) {
				MainControl.logger.info("New handler discount: " + discount.get(new Integer(1)));
				session.setAttribute("CURRENT_NEW_HANDLER_DISCOUNT", discount.get(new Integer(1)));
			} else if (type == LEVEL_TYPE_APOTHEKER) {
				MainControl.logger.info("New apotheker discount: " + discount.get(new Integer(1)));
				session.setAttribute("CURRENT_NEW_APOTHEKER_DISCOUNT", discount.get(new Integer(1)));
			}
		} else if (type == LEVEL_TYPE_CUSTOMER) {
			MainControl.logger.info("Customer discount: " + discount.get(new Integer(1)));
			session.setAttribute("CURRENT_CUSTOMER_DISCOUNT", discount.get(new Integer(1)));
		}
	}
	
}
