package org.ofbiz.extended.primavera;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.entity.GenericDelegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityConditionList;
import org.ofbiz.entity.condition.EntityExpr;
import org.ofbiz.entity.condition.EntityOperator;

import pt.link.utils.format.FormElementUtils;
import pt.link.utils.format.FormattingException;
import pt.link.utils.format.FormattingUtils_XML;


public class Events {
	public static final String module = Events.class.getName();

	public static String listVouchers(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		List vouchers = new ArrayList();
		FormElementUtils formatUtils;
		List vouchersList;
		
		String parameter = request.getParameter("sinceHours");
		int sinceHours = 1;
		if(parameter !=null)
			sinceHours = Integer.parseInt(parameter);

		GenericDelegator delegator = (GenericDelegator) request
				.getAttribute("delegator");
		try {
			formatUtils = FormattingUtils_XML
					.getInstance("/csv-elements.properties");

			java.util.Calendar cal = java.util.Calendar.getInstance();
			cal.add(Calendar.HOUR, -sinceHours);

			Timestamp someTimeAgo = UtilDateTime.toTimestamp(cal.getTime());

			List mainCondList = UtilMisc.toList(new EntityExpr("statusId",
					EntityOperator.EQUALS, "ITEM_COMPLETED"));
			mainCondList.add(new EntityExpr("entryDate",
					EntityOperator.GREATER_THAN_EQUAL_TO, someTimeAgo));
			EntityCondition mainCond = new EntityConditionList(mainCondList,
					EntityOperator.AND);

			vouchersList = delegator.findByCondition("vouchers", mainCond,
					null, null);

		} catch (Exception e) {
			Debug.logError(e, module);
			throw e;
		}

		System.out.println("vouchers list size = " + vouchersList.size());
		for (Iterator it = vouchersList.iterator(); it.hasNext();) {
			GenericValue voucherValue = (GenericValue) it.next();
			Bean bean = new Bean();

			try {
				String pid = voucherValue.getString("productId");
				if (pid != null)
					bean.elements.add(new Element("PID", pid));

				Date entryDate = voucherValue.getTimestamp("entryDate");
				if (entryDate != null) {
					String padded = entryDate == null ? "" : formatUtils
							.getElement("SV").pad(entryDate);
					bean.elements.add(new Element("SV", padded));
				}

				String paddedSQ = formatUtils.getElement("SQ").pad(
						voucherValue.getString("quantity"));
				bean.elements.add(new Element("SQ", paddedSQ));

				String paddedSPU = formatUtils.getElement("SPU").pad(
						voucherValue.getString("unitPrice"));
				bean.elements.add(new Element("SPU", paddedSPU));

				
				String orderItemSeqId = voucherValue.getString("orderItemSeqId");
				String sr = voucherValue.getString("productId") + orderItemSeqId;
				bean.elements.add(new Element("SR", sr));

				String orderId = voucherValue.getString("orderId");
				
				bean.elements.add(new Element("SPR", orderId));

				// workOrderFulFillment
				List list = delegator.findByAnd("WorkOrderItemFulfillment",
						UtilMisc.toMap("orderId", orderId));
				if (list.size() > 0) {
					GenericValue value = (GenericValue) list.get(0);
					String workEffortId = value.getString("workEffortId");

					GenericValue workEffort = delegator.findByPrimaryKey(
							"WorkEffort", UtilMisc.toMap("workEffortId",
									workEffortId));
					Date startDate = workEffort
							.getTimestamp("estimatedStartDate");
					Date endDate = workEffort
							.getTimestamp("estimatedCompletionDate");

					String paddedSRSD = formatUtils.getElement("SRSD").pad(
							startDate);
					bean.elements.add(new Element("SRSD", paddedSRSD));
					String paddedSRFD = formatUtils.getElement("SRFD").pad(
							endDate);
					bean.elements.add(new Element("SRFD", paddedSRFD));
				} else {
					bean.elements.add(new Element("SRSD", ""));
					bean.elements.add(new Element("SRFD", ""));
				}

				String visitValue = (String) voucherValue
						.getString("initialLocale");
				String tongue;
				if (visitValue != null && visitValue.length() > 0) {
					tongue = visitValue.split("_")[0];
				} else
					tongue = "";
				bean.elements.add(new Element("SLC", tongue));
				vouchers.add(bean);
			} catch (Exception e) {
				Debug.logError(e, module);
				throw e;
			}

		}
		request.setAttribute("csvData", vouchers);

		return "success";
	}
	
	
	public static String listPriceChanges(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String parameterSinceDays = request.getParameter("sinceDays");
		int sinceDays = 0;
		if(parameterSinceDays != null)
			sinceDays = Integer.parseInt(request.getParameter("sinceDays"));
		
		ArrayList priceChangesList = new ArrayList();
		List priceList;

		GenericDelegator delegator = (GenericDelegator) request
				.getAttribute("delegator");
		FormElementUtils formatUtils;
		try {
			formatUtils = FormattingUtils_XML
					.getInstance("/csv-elements.properties");
			List mainCondList = new ArrayList();

			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DATE, -sinceDays);
			Timestamp activationDateLowerBound = UtilDateTime.toTimestamp(cal.getTime());
			mainCondList.add(new EntityExpr("activationDate",
					EntityOperator.GREATER_THAN_EQUAL_TO, activationDateLowerBound));

			int daysAhead = (int) UtilProperties.getPropertyNumber("integracao.primavera.properties","daysAhead");
			
			cal.add(Calendar.DATE, sinceDays + daysAhead);
			Timestamp activationDateUpperBound = UtilDateTime.toTimestamp(cal.getTime());
			mainCondList.add(new EntityExpr("activationDate",
					EntityOperator.LESS_THAN_EQUAL_TO, activationDateUpperBound));
			
			EntityCondition mainCond = new EntityConditionList(mainCondList,
					EntityOperator.AND);

			priceList = delegator.findByCondition("priceChangeV2", mainCond,
					null, null);
		} catch (FormattingException e) {
			throw e;
		} catch (GenericEntityException e) {
			throw e;
		}

		for (Iterator it = priceList.iterator(); it.hasNext();) {
//			try {
				Bean bean = new Bean();
				GenericValue priceValue = (GenericValue) it.next();
				bean.elements.add(new Element("PID", priceValue
						.getString("productId")));
				
				Date rawVspd = priceValue.getTimestamp("activationDate");
				String paddedVspd = rawVspd == null ? "" : formatUtils.getElement("VSPD").pad(rawVspd);
				bean.elements.add(new Element("vspd", paddedVspd));

				Date rpsd = priceValue.getDate("fromDate");
				if(rpsd != null){
					String paddedRpsd = rpsd == null ? "" : formatUtils.getElement("RPSD").pad(rpsd);
					bean.elements.add(new Element("rpsd", paddedRpsd));
				}
				else{
					bean.elements.add(new Element("rpsd", ""));
				}
				
				Date rpfd = priceValue.getDate("thruDate");
				if(rpfd!=null){
					String paddedRpfd = rpfd == null ? "" : formatUtils.getElement("RPFD").pad(rpfd);
					bean.elements.add(new Element("rpfd", paddedRpfd));
				}
				else{
					bean.elements.add(new Element("rpfd", ""));
				}
				
				String rawUp = priceValue.getString("price");
				String paddedUp = rawUp == null ? "" : formatUtils.getElement(
						"UP").pad(rawUp);
				bean.elements.add(new Element("up", paddedUp));

				priceChangesList.add(bean);
//			} catch (Exception3DS e) {
//				Debug.logError(e, module);
//				throw e;
//			}
		}

		request.setAttribute("csvData", priceChangesList);
		return "success";
	}

}
