package com.reallinkbilling.delete;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.cipher.EncryptionDecryption;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.update.UpdateProductStockDetails;
import com.reallinkbilling.utils.LabelCapSchema;

public class DeleteProductionDetails extends ActionSupport implements SessionAware{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 6894624153115864441L;
	private HttpSession session;
	private SessionMap<String,Object> sessionMap;
	private String key;
	public String execute() {
		 
		String result = "login";
		session=ServletActionContext.getRequest().getSession(false); 
		
	        if(session==null || session.getAttribute("login")==null){ 
	        	addActionMessage("Please Logout and Login again !");
	        	result = "error";
	        }  
	        else{ 	
	        	
	        	String productionId = EncryptionDecryption.decrypt(this.getKey());
	        	
	        
	        	Connection connection = null;
    			PreparedStatement preparedStatement = null;
    			ResultSet resultSet = null;
    			String db = (String) this.getSessionMap().get("db");
    			
    			String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    		String sql = "";
    			try
    			{
    				connection = GetDBConnection.getDBConnection(db);
    				LabelCapSchema.ensure(this.getSessionMap());
    				connection.setAutoCommit(false);
    				
    				Map<String,Float> productDetailsMap = new HashMap<String,Float>();
    				
    				sql = "SELECT "
    						+ "product_id,"
    						+ "product_quantity "
    						+ "FROM "
    						+ "production_product_details_master "
    						+ "WHERE "
    						+ "shop_id = ? "
    						+ "AND "
    						+ "shop_code = ? "
    						+ "AND "
    						+ "production_id = ? ";
    				
    				preparedStatement = connection.prepareStatement(sql);
    				
    				preparedStatement.setString(1, shopId);
    				preparedStatement.setString(2, shopCode);
    				preparedStatement.setString(3, productionId);
    				
    				resultSet = preparedStatement.executeQuery();
    				
    				while(resultSet.next())
    				{
    					productDetailsMap.put(resultSet.getString(1), resultSet.getFloat(2));
    				}
    				
    				int productCount = productDetailsMap.size();
    				
    				boolean productStockUpdated = false;
    				
    				for(String productId : productDetailsMap.keySet())
    				{
    					productStockUpdated = UpdateProductStockDetails.addStockToCurrentStock(connection, this.getSessionMap(), productId, productDetailsMap.get(productId), 0F);
    				}
    				
    				
    				if(productStockUpdated)
    				{
    					
    					if(resultSet != null)
    					{
    						resultSet.close();
    						resultSet = null;
    					}
    					if(preparedStatement != null)
    					{
    						preparedStatement.close();
    						preparedStatement = null;
    					}
    					
    					sql = "SELECT "
    							+ "finished_product_id,"
    							+ "production_quantity,"
    							+ "product_id "
    							+ "FROM "
    							+ "shop_production_details_master "
    							+ "WHERE "
    							+ "shop_id = ? "
    							+ "AND "
    							+ "shop_code = ? "
    							+ "AND "
    							+ "production_id = ? ";
    					
    					preparedStatement = connection.prepareStatement(sql);
    					
    					preparedStatement.setString(1, shopId);
    					preparedStatement.setString(2, shopCode);
    					preparedStatement.setString(3, productionId);
    					
    					resultSet = preparedStatement.executeQuery();
    					String finishedProductId = "";
    					Float finishedProductQty = 0.0F;
    					String stockProductId = "";
    					if(resultSet.next())
    					{
    						finishedProductId = resultSet.getString(1);
    						finishedProductQty = resultSet.getFloat(2);
    						stockProductId = resultSet.getString(3);
    					}
    					if(stockProductId == null || stockProductId.trim().equals("") || stockProductId.equals("0"))
    					{
    						stockProductId = finishedProductId;
    					}
    					
    					boolean finishedStockMinus = UpdateProductStockDetails.minusStockToCurrentStock(connection, this.getSessionMap(), stockProductId, finishedProductQty);
    			
    					if(finishedStockMinus && productStockUpdated)
    					{
    						if(preparedStatement != null)
        					{
        						preparedStatement.close();
        						preparedStatement = null;
        					}
    						
    						sql = "DELETE "
    								+ "FROM "
    								+ "shop_production_details_master "
    								+ "WHERE "
        							+ "shop_id = ? "
        							+ "AND "
        							+ "shop_code = ? "
        							+ "AND "
        							+ "production_id = ? ";
    						

        					preparedStatement = connection.prepareStatement(sql);
        					
        					preparedStatement.setString(1, shopId);
        					preparedStatement.setString(2, shopCode);
        					preparedStatement.setString(3, productionId);
        					
        					int rowsDeleted = preparedStatement.executeUpdate();
        					
        					if(rowsDeleted > 0)
        					{
        						if(preparedStatement != null)
            					{
            						preparedStatement.close();
            						preparedStatement = null;
            					}
        						
        						sql = "DELETE "
        								+ "FROM "
        								+ "production_product_details_master "
        								+ "WHERE "
            							+ "shop_id = ? "
            							+ "AND "
            							+ "shop_code = ? "
            							+ "AND "
            							+ "production_id = ? ";
            					
            					preparedStatement = connection.prepareStatement(sql);
            					
            					preparedStatement.setString(1, shopId);
            					preparedStatement.setString(2, shopCode);
            					preparedStatement.setString(3, productionId);
            					
            					int rowsDeletedProduct = preparedStatement.executeUpdate();
            					
            					if(rowsDeletedProduct == productCount)
            					{
            						connection.commit();
            						result = SUCCESS;
            						addActionMessage("Production details deleted successfully!");
            					}
            					else
            					{
            						connection.rollback();
            						result = ERROR;
            						addActionError("Production details not deleted as couldn't match deleted rows and product count!");
            						
            					}
        					}
        					else
        					{
        						connection.rollback();
        						result = ERROR;
        						addActionError("Production details not deleted as couldn't delete production details!");
        					}
        					
        					
    					}else
    					{
    						connection.rollback();
    						result = ERROR;
    						addActionError("Production details not deleted as couldn't update all product stock!");
    					}
    				}
    				else
    				{
    					connection.rollback();
    					result = ERROR;
    					addActionError("Production details not deleted as couldn't update product stock!");
    				}
    			}
    			catch (SQLException e) {
					result = "error";
					
					addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Customer details not added !");
				} catch (IOException e) {
					
					result = "error";						
					addActionError(e.getMessage()+" || "+e.getCause()+" || Customer details not added !");
				}finally {
					if(resultSet != null)
					{
						try {resultSet.close(); resultSet = null;} catch (SQLException e) {}
					}
					if(preparedStatement != null)
					{
						try {preparedStatement.close(); preparedStatement = null;} catch (SQLException e) {}
					}
					if(connection != null)
					{
						
						try {connection.close(); connection = null;}catch (SQLException e) {}
					}
					
				}
	        	result = SUCCESS;
	        }
	        
	        return result;
	}
	
	


	public HttpSession getSession() {
		return session;
	}




	public void setSession(HttpSession session) {
		this.session = session;
	}




	public String getKey() {
		return key;
	}




	public void setKey(String key) {
		this.key = key;
	}




	public static long getSerialversionuid() {
		return serialVersionUID;
	}




	public SessionMap<String, Object> getSessionMap() {
		return sessionMap;
	}




	public void setSessionMap(SessionMap<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}




	public void setSession(Map<String, Object> map) {  
	    sessionMap=(SessionMap<String, Object>)map;  
	}






}
