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

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

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

/**
 * @author Suveges Gyorgy
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class ordersearchaccept extends PageActionHandler {
    private static Object mutex = new Object();
    /**
     * 
     */
    public ordersearchaccept() {
        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 {
        org.apache.log4j.Logger logger = MainControl.logger;
        HttpSession session = request.getSession();
        synchronized (mutex) {
	        
	        Map m = (Map) session.getAttribute("list_orders.jsp"+request.getParameter("status"));
	       
	        //ez ki volt kommentelve
	        // logger.info("from: "+OrderHelper.getVal(m,"status")+" to: "+OrderHelper.getVal(m,"toStatus"));
	        
	        //ezt en kommenteltem ki : Peter
	        int statusFrom = Integer.valueOf(OrderHelper.getVal(m, "status")).intValue();
	        
	        //ezeket hozzáirtam: Peter
	        //int statusFrom = Integer.valueOf((String)session.getAttribute("orderstatus")).intValue();
	        
	        //en kommenteltem ki: Peter
	        if (OrderHelper.getVal(m, "toStatus").equals("")) return;
	        int statusTo = Integer.valueOf(OrderHelper.getVal(m,"toStatus")).intValue();
	        
	        //int statusTo = Integer.valueOf((String)session.getAttribute("orderTostatus")).intValue();
	        
	        
	        //ezt en kommenteltem ki:P
	        String[] ids = OrderListHelper.getVal(m, "order_id"); 
	        
	        //En raktem be: Peter
	        //String[] ids = (String[])session.getAttribute("orderids");
	        
	        if (ids == null) return;
	        Integer roleId = Integer.valueOf((String) session.getAttribute("USER_LOGGED_LEVEL_ID"));
	        Integer uid = Integer.valueOf((String) session.getAttribute("USER_LOGGED_ID"));
	        
	        
	        Transaction tx = null;
	        try {
	            Session  hsession = HibernateUtil.currentSession();
	            java.sql.Connection conn = hsession.connection();
	            
	           // conn.setTransactionIsolation(java.sql.Connection.TRANSACTION_REPEATABLE_READ);
	            tx = hsession.beginTransaction();
	            
	            PersistableObject rights = new PersistableObject("order_status_rights", new String[]{"role_id","order_status_id"});
	            rights.set("role_id", roleId);
	            rights.set("order_status_id", new Integer(statusFrom));
	            rights.load(conn);
	            String nextProc = (String) rights.get("nextproc");
	            String storno = (String) rights.get("storno");
	            
	            String right = null;
	            if (statusTo!=90) {
	            	if (nextProc==null || nextProc.equalsIgnoreCase("x"))
	            		throw new EvolutionException(LocaleSupport.getLocalizedMessage(pageContext, "NO_RIGHT"));
	            	right = nextProc;
	            } else {
	            	if (storno==null || storno.equalsIgnoreCase("x"))
	            		throw new EvolutionException(LocaleSupport.getLocalizedMessage(pageContext, "NO_RIGHT"));
	            	right = storno;
	            }
	            ObjectSearch os = new ObjectSearch();
	            
	            List l = os.search(conn, "select id from order_header where order_status_id = ? and ordered_by in (select * from "+right+"(?))", new Object[]{new Integer(statusFrom), uid});
	            Set orderIdsInStatus = new TreeSet();
	            for (int i=0; i<l.size(); i++) { 
	                PersistableObject po = (PersistableObject) l.get(i);
	                orderIdsInStatus.add(po.get("id"));
	            }
	            
	            Set orderids = new TreeSet();
	            Set preFailedOrders = new TreeSet();
	            for (int i=0; i<ids.length; i++) {
	                Long id = new Long(ids[i]);
	                if (orderIdsInStatus.contains(id)) orderids.add(id);
	                else preFailedOrders.add(id);
	            }
	        
		        Workflow wf = Workflow.getInstance(statusFrom, statusTo);
		        wf.setRequest(request);
		        wf.setResponse(response);
		        wf.performFlow(conn, orderids);
		        java.sql.Connection oldConn = conn;
		        hsession = HibernateUtil.currentSession();
		        conn = hsession.connection();
		        
		        if (oldConn==conn) {
		        	logger.info("SQL Connection didn't change. Commiting");
		        	tx.commit();
		            HibernateUtil.closeSession();
		        }
		        
		        sentToResponse = wf.sentToResponse();
		        Set failedOrders = wf.getFailedOrders();
		        failedOrders.addAll(preFailedOrders);
		        if (!m.containsKey("failed_orders") && !m.containsKey("passed_orders")) {
		        	
		        	m.put("failed_orders", failedOrders);
			        m.put("passed_orders", wf.getPassedOrders());
		        }
		        
		        logger.info("size of failed orders: "+failedOrders.size());
		        logger.info("size of passed orders: "+wf.getPassedOrders().size());
	        } catch (Exception e) {
	            logger.error("Error occured while changing status. Rolling back", e);
	            if (tx!=null)
	                tx.rollback();
	            
	            throw e;
	            
	        }
        }

    }

}
