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

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.*;
import java.util.*;
import java.text.*;

import org.hibernate.Session;
import org.hibernate.Transaction;

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

public class orderbonusdatechange extends PageActionHandler {

	protected void handle(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();
        Map m = (Map) session.getAttribute("list_orders.jsp"+request.getParameter("status"));
        m.remove("order_id");
        String[] ids = OrderListHelper.getVal(m, "bonus_date");
        logger.info(" Bonus_date_size: "+ids.length);
        if (ids.length==0) {
        	logger.info("There is no bonus date to change");
        	return; 
        }

        String[] orderIds = new String[ids.length];
        Map newBonusDates = new HashMap();
        
        for (int i=0; i<ids.length; i++) {
        	String[] temp = ids[i].split(":");
        	orderIds[i] = temp[0];
        	newBonusDates.put(Long.valueOf(orderIds[i]), java.sql.Date.valueOf(temp[1]));
        }
        
        Session hsession = HibernateUtil.currentSession();
        Transaction tx = null;
        try {
        	tx = hsession.beginTransaction();	
	        Connection conn = hsession.connection();
	        ObjectSearch os = new ObjectSearch("order_header", "id");
	        List list = os.search(conn, "select id, bonus_date from order_header where "+Tools.arrayToSql("id", orderIds, false));
	        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
	        for (int i=0; i<list.size(); i++) {
	        	PersistableObject order = (PersistableObject) list.get(i);
	        	java.sql.Date oldBonusDate = (java.sql.Date) order.get("bonus_date");
	        	java.sql.Date newBonusDate = (java.sql.Date) newBonusDates.get(order.get("id"));
	        	
	        	if (!oldBonusDate.equals(newBonusDate)) {
	        		logger.info(" Bonus date of order "+order.get("id")+" has been changed ("+sdf.format(oldBonusDate)+"-> "+sdf.format(newBonusDate)+")");
	        		order.set("bonus_date", newBonusDate);
	        		order.update(conn);
	        	} 
	        	/*else
	        		logger.info(" Bonusdate at order "+order.get("id")+" didn't change ("+sdf.format(oldBonusDate)+"-> "+sdf.format(newBonusDate)+")");*/
	        		
	        	
	        	
	        }
	        
	        tx.commit();
	        HibernateUtil.closeSession();
        } catch (Exception e) {
        	logger.error("error while changing bonus date. Rolling back",e);
        	if (tx!=null)
        		tx.rollback();
        	
        	throw e;
        		
        }
        
        
        	
        
	}

}
