package com.reallinkbilling.add;


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.HashMap;
import java.util.Map;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.reallinkbilling.DAO.RejectionProductListProductDAO;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.update.UpdateProductStockDetails;
import com.reallinkbilling.utils.GetProductDetailsUtil;
import com.opensymphony.xwork2.ActionSupport;

public class SaveRejectionDetails extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 6208411094853732491L;
	private SessionMap<String,Object> sessionMap;  
	private ArrayList<RejectionProductListProductDAO> rejectionProductList ;
	private Boolean rejectionSaved = false;
	
	private String rejectionAddDate;
	private String batchId;
	
	public String execute() {
		 
		String result = "login";
	
		
	        if(this.getSessionMap()==null || this.getSessionMap().get("login")==null){ 
	        	addActionMessage("Please Logout and Login again !");
	        	result = "login";
	        }  
	        else{
	        		

	    		this.setRejectionProductList((ArrayList<RejectionProductListProductDAO>) this.getSessionMap().get("rejectionList"));
	    		
	    		
	         	
				String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    	
				Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;
			
					
				String sql = "";
				String db = (String)  this.getSessionMap().get("db");
				
				try
				{
					connection = GetDBConnection.getDBConnection(db);
					connection.setAutoCommit(false);
					
					if(this.getRejectionProductList() != null)
		        	{
						if(this.getRejectionProductList().size() > 0)
						{
							
							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;
				        	}
				        	
				        	Date d = new Date();
				        	SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
				        	
				        	  java.util.Date date = new java.util.Date();
			        	      long t = date.getTime();	        	     
			        	      java.sql.Time time = new java.sql.Time(t);
						   
							sql =  "INSERT INTO "
									+ "rejection_details "
									+ "("
									+ "shop_id,"
									+ "shop_code,"
									+ "rejection_date,"
									+ "entry_date,"
									+ "entry_time,"
									+ "batch_id,"
									+ "product_all_details,"
									+ "product_id,"
									+ "product_name,"
									+ "quantity,"
									+ "purchase_rate,"
									+ "total_purchase_amount,"
									+ "tax_rate,"
									+ "tax_amount,"
									+ "total_amount,"
									+ "responsible_person,"
									+ "entry_by) "
									+ "VALUES "
									+ "(?,?,STR_TO_DATE(?,'%d-%m-%Y'),STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,?,?)";
							
							preparedStatement = connection.prepareStatement(sql);
							
							
							for(RejectionProductListProductDAO dao : this.getRejectionProductList())
							{
								
								this.setRejectionAddDate(dao.getRejectionDate());
								this.setBatchId(dao.getBatchId());
								
								HashMap<String,Object> productDetails = GetProductDetailsUtil.getProductDetailsById(this.getSessionMap(), dao.getProductId());
								
								
								
								float stockConRatio  =  (Float) productDetails.get("STOCKCONVERSIONRATIO");
				        	 
								float productTotalAmount = dao.getQuantity() * ((Float) productDetails.get("PURCHASERATE") / stockConRatio);
								float taxPerCentage = (Float) productDetails.get("TAXPERCENTAGE");
								float taxAmount = productTotalAmount  * ( taxPerCentage/ 100.0F);
										
								preparedStatement.setString(1, shopId);
								preparedStatement.setString(2, shopCode);
								preparedStatement.setString(3, dao.getRejectionDate());
								preparedStatement.setString(4, dateFormat.format(d));
								preparedStatement.setTime(5, time);
								preparedStatement.setString(6, dao.getBatchId());
								preparedStatement.setString(7, dao.getProductAllDetails());
								preparedStatement.setString(8, dao.getProductId());
								preparedStatement.setString(9, dao.getProductName());
								preparedStatement.setFloat(10, dao.getQuantity());
								preparedStatement.setFloat(11, (Float) productDetails.get("PURCHASERATE"));
								preparedStatement.setFloat(12, productTotalAmount);
								preparedStatement.setString(13, (String) productDetails.get("TAXID"));
								preparedStatement.setFloat(14, taxAmount);
								preparedStatement.setFloat(15, productTotalAmount + taxAmount);
								preparedStatement.setString(16, "");
								preparedStatement.setString(17, entryBy);
								
								preparedStatement.addBatch();
								
							}
							
							int [] k = preparedStatement.executeBatch();
							
							boolean stockMinus = false;
							
							if(k.length == this.getRejectionProductList().size())
							{
								for(RejectionProductListProductDAO dao : this.getRejectionProductList())
								{
									stockMinus = UpdateProductStockDetails.minusStockToCurrentStock(connection, this.getSessionMap(), dao.getProductId(), dao.getProductName(), dao.getQuantity(), 0.0f);
			        	        
								}
								
								if(stockMinus)
								{
									this.setRejectionSaved(true);
									connection.commit();
									result = SUCCESS;
									addActionMessage("Rejection Details added Successfully!");
								}
								else
								{
									connection.rollback();
									result = ERROR;
									
									addActionError("Rejection details not added! Please try again! Error while stock minus!");
								}
							}
							else
							{
								connection.rollback();
								result = ERROR;								
								addActionError("Rejection details not added! Please try again!");
								
							}
							
							
						}
						else
						{
							connection.rollback();
							result = ERROR;
							addActionError("Couldnt find list of products!");
						}
						
		        	}
					else
					{
						connection.rollback();
						result = ERROR;
						addActionError("Couldnt find list of products 2!");
					}
					
					this.getSessionMap().put("rejectionList", this.getRejectionProductList());
				}
				catch (SQLException e) {
					
					try {
						connection.rollback();
					} catch (SQLException e1) {}
					result = ERROR;
					
					addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Something Went Wrong !");
				}
				catch (Exception e) {
					
					
					try {
						connection.rollback();
					} catch (SQLException e1) {}
					result = ERROR;
					
					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 ArrayList<RejectionProductListProductDAO> getRejectionProductList() {
		return rejectionProductList;
	}


	public void setRejectionProductList(ArrayList<RejectionProductListProductDAO> rejectionProductList) {
		this.rejectionProductList = rejectionProductList;
	}


	public static long getSerialversionuid() {
		return serialVersionUID;
	}


	public Boolean getRejectionSaved() {
		return rejectionSaved;
	}


	public void setRejectionSaved(Boolean rejectionSaved) {
		this.rejectionSaved = rejectionSaved;
	}


	public String getRejectionAddDate() {
		return rejectionAddDate;
	}


	public void setRejectionAddDate(String rejectionAddDate) {
		this.rejectionAddDate = rejectionAddDate;
	}


	public String getBatchId() {
		return batchId;
	}


	public void setBatchId(String batchId) {
		this.batchId = batchId;
	}


	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;  
	}
	

}



