package com.reallinkbilling.add;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
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.DAO.FinishedProductInfoDAO;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.update.UpdateProductStockDetails;
import com.reallinkbilling.utils.LabelCapProduct;
import com.reallinkbilling.utils.LabelCapProductUtil;
import com.reallinkbilling.utils.LabelCapSchema;
import com.reallinkbilling.utils.PackingMasterOptions;

public class AddNewProduction extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = -7316316970430227943L;
	
	private SessionMap<String,Object> sessionMap;  
	private HttpSession session;
	private String finishedProductId;
	private String batchId;
	private Float productionQuantity;
	private String shift;
	private String productionBy;
	private String description;
	private String productionDateTime;
	
	private Map<String,String> finishedProductList = new LinkedHashMap<String,String>();
	private Map<String,String> labelList = new LinkedHashMap<String,String>();
	private Map<String,String> capList = new LinkedHashMap<String,String>();
	private String labelId;
	private String capId;
	

	public String execute() {
		 
		String result = "login";
		session=ServletActionContext.getRequest().getSession(false); 
		
	        if(session==null || session.getAttribute("login")==null){ 
	        	addActionMessage("Please Login First !!!");
	        	result = "login";
	        }  
	        else{
	        	
	        	
	        	String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    		
	        	
	        	
	          java.util.Date date = new java.util.Date();
       	      long t = date.getTime();	        	     
       	      java.sql.Time time = new java.sql.Time(t);
       	      
       		Connection connection = null;
			PreparedStatement preparedStatement= null;
			ResultSet resultSet = null;
			
			String sql = "";
			String db = (String) this.getSessionMap().get("db");
	
			List<FinishedProductInfoDAO> finishedProductInfoList = new ArrayList<FinishedProductInfoDAO>();
			
			try
    		{
    			connection = GetDBConnection.getDBConnection(db);
    			LabelCapSchema.ensure(this.getSessionMap());
    			connection.setAutoCommit(false);
    			sql = "SELECT "
    					+ "product_id,"
    					+ "product_quantity_required "
    					+ "FROM "
    					+ "shop_finished_product_details_master "
    					+ "WHERE "
    					+ "finished_product_id = ? "
    					+ "AND "
    					+ "shop_id = ? "
    					+ "AND "
    					+ "shop_code = ?";
    			
    			preparedStatement = connection.prepareStatement(sql);
    			preparedStatement.setString(1, this.getFinishedProductId());
    			preparedStatement.setString(2, shopId);
    			preparedStatement.setString(3, shopCode);
    			
    			resultSet = preparedStatement.executeQuery();
    			while(resultSet.next())
    			{
    				FinishedProductInfoDAO dao = new FinishedProductInfoDAO();
    				
    				dao.setProductId(resultSet.getString(1));
    				dao.setProductQuantity(resultSet.getFloat(2));
    				
    				finishedProductInfoList.add(dao);
    			}
    			
    			
    			
    			boolean productStockUpdated = false;
    			for(FinishedProductInfoDAO dao : finishedProductInfoList)
    			{
    				productStockUpdated = UpdateProductStockDetails.minusStockToCurrentStock(connection, this.getSessionMap(), dao.getProductId(), dao.getProductName(),this.getProductionQuantity()*dao.getProductQuantity(),0F);
    			}
	        	
    			if(resultSet != null)
    			{
    				resultSet.close();
    				resultSet = null;
    			}
    			
    			if(preparedStatement != null)
    			{
    				preparedStatement.close();
    				preparedStatement = null;
    			}
	        
    			LabelCapProduct comboProduct = null;
    			if(productStockUpdated)
    			{
    				comboProduct = LabelCapProductUtil.findOrCreate(connection, this.getSessionMap(), this.getFinishedProductId(), this.getLabelId(), this.getCapId());
    				int newProdctionID = 1;
    				sql = "SELECT "
    						+ "production_id "
    						+ "FROM "
    						+ "shop_production_details_master "
    						+ "WHERE "
    						+ "shop_id = ? "
    						+ "AND "
    						+ "shop_code = ? "
    						+ "ORDER BY production_id desc LIMIT 1";
    				
    				preparedStatement = connection.prepareStatement(sql);
    				
    				preparedStatement.setString(1, shopId);
    				preparedStatement.setString(2, shopCode);
    				
    				resultSet = preparedStatement.executeQuery();
    				
    				if(resultSet.next())
    				{
    					newProdctionID = resultSet.getInt(1) + 1 ;
    				}
    				
    				if(resultSet != null)
        			{
        				resultSet.close();
        				resultSet = null;
        			}
        			
        			if(preparedStatement != null)
        			{
        				preparedStatement.close();
        				preparedStatement = null;
        			}
        			
        			String fullUserName = (String) this.getSessionMap().get("userFullName");
		        	
		        	String splitUserName [] = new String[5];
        			
        			String entryBy = "";
		        	try
		        	{
		        		splitUserName = fullUserName.split(" ");
		        		entryBy = splitUserName[0];
		        		
		        	}catch(Exception e)
		        	{
		        		entryBy =fullUserName;
		        	}
		        	
        			sql = "INSERT INTO "
        					+ "shop_production_details_master "
        					+ "("
        					+ "production_id,"
        					+ "shop_id,"
        					+ "shop_code,"
        					+ "finished_product_id,"
        					+ "production_date,"
        					+ "production_time,"
        					+ "production_quantity,"
        					+ "batch_id,"
        					+ "shift,"
        					+ "production_by,"
        					+ "production_details,"
        					+ "entry_by,"
        					+ "label_id,"
        					+ "cap_id,"
        					+ "product_id) "
        					+ "VALUES "
        					+ "(?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?)";
        			
        			preparedStatement = connection.prepareStatement(sql);
        			
        			preparedStatement.setInt(1, newProdctionID);
        			preparedStatement.setString(2, shopId);
        			preparedStatement.setString(3, shopCode);
        			preparedStatement.setString(4, this.getFinishedProductId());
        			preparedStatement.setString(5, this.getProductionDateTime());
        			preparedStatement.setTime(6, time);
        			preparedStatement.setFloat(7, this.getProductionQuantity());
        			preparedStatement.setString(8, this.getBatchId().trim().toUpperCase());
        			preparedStatement.setString(9, this.getShift() == null ? "" : this.getShift().trim().toUpperCase());
        			preparedStatement.setString(10, this.getProductionBy() == null ? "" : this.getProductionBy().trim().toUpperCase());
        			preparedStatement.setString(11, this.getDescription() == null ? "" : this.getDescription().trim().toUpperCase());
        			preparedStatement.setString(12, entryBy);
        			preparedStatement.setInt(13, Integer.parseInt(this.getLabelId()));
        			preparedStatement.setInt(14, Integer.parseInt(this.getCapId()));
        			preparedStatement.setInt(15, Integer.parseInt(comboProduct.getProductId()));
        			
        			int i = preparedStatement.executeUpdate();
        			
        			if(i > 0)
        			{
        				
            			if(preparedStatement != null)
            			{
            				preparedStatement.close();
            				preparedStatement = null;
            			}
            			
            			
            			sql = "INSERT INTO "
            					+ "production_product_details_master "
            					+ "( "
            					+ "shop_id,"
            					+ "shop_code,"
            					+ "production_id,"
            					+ "product_id,"
            					+ "product_quantity) "
            					+ "VALUES "
            					+ "(?,?,?,?,?)";
            			preparedStatement = connection.prepareStatement(sql);
            			for(FinishedProductInfoDAO dao : finishedProductInfoList)
            			{
            				preparedStatement.setString(1, shopId);
            				preparedStatement.setString(2, shopCode);
            				preparedStatement.setInt(3, newProdctionID);
            				preparedStatement.setInt(4, Integer.parseInt(dao.getProductId()));
            				preparedStatement.setFloat(5, this.getProductionQuantity()* dao.getProductQuantity());
            				
            				preparedStatement.addBatch();
            			}
            			
            			int rowInsetred [] = preparedStatement.executeBatch();
            			
            			if(rowInsetred.length == finishedProductInfoList.size())
            			{

                			if(preparedStatement != null)
                			{
                				preparedStatement.close();
                				preparedStatement = null;
                			}
                			
                			
                			boolean addFinishedProStock = UpdateProductStockDetails.addStockToCurrentStock(connection, this.getSessionMap(), comboProduct.getProductId(), this.getProductionQuantity(),0F);
            				
                			if(addFinishedProStock)
                			{
	                			result = SUCCESS;
	            				connection.commit();
	            				try
	            				{
	            					LabelCapProductUtil.syncSessionStock(this.getSessionMap(), comboProduct, this.getProductionQuantity());
	            				}
	            				catch(Exception stockSyncError)
	            				{
	            				}
	            				String productMessage = "Production details added successfully! Product: " + comboProduct.getProductName();
	            				if(comboProduct.isNewlyCreated())
	            				{
	            					productMessage = productMessage + " New product added in product master.";
	            				}
	            				addActionMessage(productMessage);
                			}
                			else
                			{
                				result = ERROR;
                				connection.rollback();
                				addActionMessage("Production details not added as could not updated finished product stock!");
                			}
            			}
            			
        			}
        			else
        			{
        				connection.rollback();
        				result = ERROR;
        				addActionError("Production details not added as could not add prduction details!");
        				
        			}
    				
    			}
    			else
    			{
    				connection.rollback();
    				result = ERROR;
    				addActionError("Production details not added as could not update stock quantity correctly! Check Stock details!");
    			}
	        }
    		catch (SQLException e) {
    			result = ERROR;
    			if(connection != null)
    			{
    				try {connection.rollback();} catch (SQLException ex) {}
    			}
    			addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Something Went Wrong!");
    			
    		} catch (IOException e) {
    			result = ERROR;
    			if(connection != null)
    			{
    				try {connection.rollback();} catch (SQLException ex) {}
    			}
    			addActionError(e.getMessage()+" || "+e.getCause()+" || Something Went Wrong!");
    			
    		} catch (Exception e) {
    			result = ERROR;
    			if(connection != null)
    			{
    				try {connection.rollback();} catch (SQLException ex) {}
    			}
    			addActionError(e.getMessage()+" || Something Went Wrong!");
    			
    		}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) {}
    			}
    			
    		}
	        }
	   
	   return result;
	      
	}


	public void validate() {
		
		if(this.getFinishedProductId() == null || this.getFinishedProductId().equals(""))
		{
			addActionError("Plesae select finished product!");
		}
		
		if(!hasActionErrors())
		{
			if(this.getLabelId() == null || this.getLabelId().equals(""))
			{
				addActionError("Please select label!");
			}
		}
		
		if(!hasActionErrors())
		{
			if(this.getCapId() == null || this.getCapId().equals(""))
			{
				addActionError("Please select cap!");
			}
		}
		
		if(!hasActionErrors())
		{
			if(this.getBatchId() == null || this.getBatchId().equals(""))
			{
				addActionError("Please provide batch ID/Number!");
			}
				
		}
		
		if(!hasActionErrors())
		{
			if(this.getProductionQuantity() == null || this.getProductionQuantity().equals(""))
			{
				addActionError("Please provide correct production quantity!");
			}
		}
		
		 	Connection connection = null;
			PreparedStatement preparedStatement= null;
			ResultSet resultSet = null;
			
			String sql = "";
			String db = (String) this.getSessionMap().get("db");
		

    		String shopId = (String) this.getSessionMap().get("shopId");
    		String shopCode = (String) this.getSessionMap().get("shopCode");
    		
			try
    		{
    			connection = GetDBConnection.getDBConnection(db);
    			LabelCapSchema.ensure(this.getSessionMap());
    			this.getFinishedProductList().clear();
    			this.getLabelList().clear();
    			this.getCapList().clear();
    			PackingMasterOptions.loadFinishedProducts(connection, shopId, shopCode, this.getFinishedProductList());
    			PackingMasterOptions.loadLabels(connection, shopId, shopCode, this.getLabelList());
    			PackingMasterOptions.loadCaps(connection, shopId, shopCode, this.getCapList());
    			
    			
    		}
    		catch (SQLException e) {
    			
    			 			
    			addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Something Went Wrong!");
    			
    		} catch (IOException e) {
    			
    				    			
    			addActionError(e.getMessage()+" || "+e.getCause()+" || Something Went Wrong!");
    			
    		}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) {}
    			}
    			
    		}
		
	}
	
	public String getFinishedProductId() {
		return finishedProductId;
	}


	public void setFinishedProductId(String finishedProductId) {
		this.finishedProductId = finishedProductId;
	}


	public String getBatchId() {
		return batchId;
	}


	public void setBatchId(String batchId) {
		this.batchId = batchId;
	}
	

	public Float getProductionQuantity() {
		return productionQuantity;
	}


	public void setProductionQuantity(Float productionQuantity) {
		this.productionQuantity = productionQuantity;
	}


	public Map<String, String> getFinishedProductList() {
		return finishedProductList;
	}


	public void setFinishedProductList(Map<String, String> finishedProductList) {
		this.finishedProductList = finishedProductList;
	}


	public SessionMap<String, Object> getSessionMap() {
		return sessionMap;
	}

	public void setSessionMap(SessionMap<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}

	public HttpSession getSession() {
		return session;
	}


	public void setSession(HttpSession session) {
		this.session = session;
	}


	public static long getSerialversionuid() {
		return serialVersionUID;
	}


	public String getShift() {
		return shift;
	}


	public void setShift(String shift) {
		this.shift = shift;
	}


	public String getProductionBy() {
		return productionBy;
	}


	public void setProductionBy(String productionBy) {
		this.productionBy = productionBy;
	}


	public String getProductionDateTime() {
		return productionDateTime;
	}


	public void setProductionDateTime(String productionDateTime) {
		this.productionDateTime = productionDateTime;
	}


	public String getDescription() {
		return description;
	}


	public void setDescription(String description) {
		this.description = description;
	}

	public Map<String, String> getLabelList() {
		return labelList;
	}

	public void setLabelList(Map<String, String> labelList) {
		this.labelList = labelList;
	}

	public Map<String, String> getCapList() {
		return capList;
	}

	public void setCapList(Map<String, String> capList) {
		this.capList = capList;
	}

	public String getLabelId() {
		return labelId;
	}

	public void setLabelId(String labelId) {
		this.labelId = labelId;
	}

	public String getCapId() {
		return capId;
	}

	public void setCapId(String capId) {
		this.capId = capId;
	}

  
	public void setSession(Map<String, Object> map) {  
	    sessionMap=(SessionMap<String, Object>)map;  
	}

}
