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.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.db.GetDBConnection;
import com.reallinkbilling.resource.CheckAlreadyAvailable;


public class AddProductToStock extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 6873323224759968604L;
	
	private HttpSession session;
	private String productName;
	private Float quantity;
	private Float quantity2;
	private boolean addQuantity2;
	private SessionMap<String,Object> sessionMap;  
	
	public String execute() throws IOException{
		 
		String result = "login";
		session=ServletActionContext.getRequest().getSession(false); 
		
	        if(session==null || session.getAttribute("login")==null){ 
	        	addActionMessage("Please Login First !!!");
	        	result = "login";
	        }  
	        else{
	        		         	
				Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;
				
				String sql = "";
				String db = (String) this.getSessionMap().get("db");
				
			
					try
					{

			        	
			        	
			        	String shopId = (String) this.getSessionMap().get("shopId");
			    		String shopCode = (String) this.getSessionMap().get("shopCode");
			    		
			    		String [] productData = this.getProductName().split("-");
			    		String productId = productData[0];
			    		String productName = productData[1];
			    		String productCode = productData[2];
			    		
			    		if(!isAddQuantity2())
			    		{
			    			this.setQuantity2(0.0F);
			    		}
			    		
			         	
						connection = GetDBConnection.getDBConnection(db);
						float dbQuantity = 0.0F;
						float newQuantity = 0.0F;
						
						float dbQuantity2 = 0.0F;
						float newQuantity2 = 0.0F;
						sql = "SELECT "
								+ "in_stock_quantity,"
								+ "in_stock_quantity_2 "
								+ "FROM "
								+ "shop_product_master "
								+ "WHERE "
								+ "product_id = ? "
								+ "AND "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? ";
						
						preparedStatement = connection.prepareStatement(sql);
						preparedStatement.setString(1, productId);
						preparedStatement.setString(2, shopId);
						preparedStatement.setString(3, shopCode);
						
						resultSet = preparedStatement.executeQuery();
						
						if(resultSet.next())
						{
							dbQuantity = resultSet.getFloat(1);
							dbQuantity2 = resultSet.getFloat(2);
						}
						
						newQuantity = dbQuantity + this.getQuantity();
						newQuantity2 = dbQuantity2 + this.getQuantity2();
						
						if(resultSet != null)
						{
							resultSet.close();
							resultSet = null;
						}
						
						if(preparedStatement != null)
						{
							preparedStatement.close();
							preparedStatement = null;
						}
						
						
						sql = "UPDATE "
								+ "shop_product_master "
								+ "SET "
								+ "in_stock_quantity = ?,"
								+ "in_stock_quantity_2 = ? "
								+ "WHERE "
								+ "product_id = ? "							
								+ "AND "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? ";
						
						
						preparedStatement = connection.prepareStatement(sql);
						preparedStatement.setFloat(1, newQuantity);	
						preparedStatement.setFloat(2, newQuantity2);	
						preparedStatement.setString(3, productId);
						preparedStatement.setString(4, shopId);
						preparedStatement.setString(5, shopCode);
						
						int i = preparedStatement.executeUpdate();
						if(i>0)
						{
						
							result = "success";
							addActionMessage("Stock Updated Successfully!");
							this.setProductName("");
							this.setQuantity(0.0F);
							this.setQuantity2(0.0F);
						}
						else
						{
							result = "error";
							addActionError("Stock not Added! Please try again!");
						}
					}
					catch (SQLException e) {
						result = "error";
						//e.printStackTrace();
						addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Stock Not Added !!!");
					} catch (IOException e) {
						result = "error";
						//e.printStackTrace();
						addActionError(e.getMessage()+" || "+e.getCause()+" || Stock Not Added");
					}finally {
						
						
						if(resultSet != null)
						{
							try {
								resultSet.close();
								resultSet = null;
							} catch (SQLException e) {
								// TODO Auto-generated catch block
								//e.printStackTrace();
							}
						}
						if(preparedStatement != null)
						{
							try {preparedStatement.close();} catch (SQLException e) {}
						}
						if(connection != null)
						{
							
							try {connection.close();}catch (SQLException e) {}
						}
						
					}
			        
			    
			      
			        
			        
			        }
			       
			        return result;
			}
	
	@Override
	public void validate() {
		
		HashMap<String, String> settings = (HashMap<String, String>) this.getSessionMap().get("shop_settings");
        
    	if(settings.get("add_quntity2").equals("TRUE"))
    	{
    		this.setAddQuantity2(true);
    	}
    	else
    	{
    		this.setAddQuantity2(false);
    	}
		
    	if(!hasActionErrors())
		{
			if(this.getQuantity() == null || this.getQuantity().equals(""))
			{
				addActionError("Please provide correct quantity!");
			}
		}
    	
    	if(isAddQuantity2())
    	{
    		if(this.getQuantity2() == null || this.getQuantity2().equals(""))
    		{
    			addActionError("Please provide 2nd quantity!");
    		}
    	}
		if(!hasActionErrors())
		{

			String isCustomerAdded = "false";
			
			String [] result = new String[2];
			
			result = new CheckAlreadyAvailable().checkAvaibility("shop_product_master", "product_name_eng", "NA", this.getProductName().split("-")[1], this.getSessionMap());
			
			
			isCustomerAdded = result[0];
			
			if(!isCustomerAdded.equals("true"))
			{
				addActionError("Product name given not found ! Please provide correct product name !");
			}	
			
		}
		
		
	
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public Float getQuantity() {
		return quantity;
	}

	public void setQuantity(Float quantity) {
		this.quantity = quantity;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	
	public boolean isAddQuantity2() {
		return addQuantity2;
	}

	public void setAddQuantity2(boolean addQuantity2) {
		this.addQuantity2 = addQuantity2;
	}

	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;  
	}

	public Float getQuantity2() {
		return quantity2;
	}

	public void setQuantity2(Float quantity2) {
		this.quantity2 = quantity2;
	}
	
	
}