package com.reallinkbilling.edit;

import java.io.File;
import java.io.FileInputStream;
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.LinkedHashMap;
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.resource.CheckAlreadyAvailable;
import com.reallinkbilling.resource.GetListResource;

public class EditProduct extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = -2794397468407641682L;
	private HttpSession session;
	private String productAddDate;
	private String productName;
	private Float puchaseRate;
	private String productNameMarathi ;
	private String productCode;
	private Float customerSalesRate;
	private Float retailerSalesRate;
	private Float dealerSalesRate;
	private String rackNumber;
	private String taxId;
	private String Alias;
	private String saleUnit;
	private String purchaseUnit;
	private String lowStockCount;
	private String hsnCode;
	private String convertQuantity;
	private String id;
	private String productCodeOld;
	private File productImage;
	
	private Map<String,String> taxList = new LinkedHashMap<String,String>();
	private Map<String,String> unitList = new LinkedHashMap<String,String>();
	private Map<String,String> supplierList = new LinkedHashMap<String,String>();
	
	private Map<String,String> customerSearchOptionList = new HashMap<String,String>();
	private String customerSearchOption;
	private String defaultValue;
	
	private Map<String,String> discountTypeList = new LinkedHashMap<String,String>();
	private String discountType;
	
	private SessionMap<String,Object> sessionMap;  
	
	private Float defaultBarCodeQty;
	private Float mrprate;
	private Float discount;
	private Float salePrice;
	@Override
	synchronized 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
        {     	this.getCustomerSearchOptionList().put("BYNAME", "BY NAME");
		    	this.getCustomerSearchOptionList().put("BYMOBILE", "BY MOBILE");
		    	this.getCustomerSearchOptionList().put("BYADDRESS","BY ADDRESS");
				this.setCustomerSearchOption("BYNAME");
				this.setDefaultValue("BYNAME");
        	
        	String shopId = (String) this.getSessionMap().get("shopId");
    		String shopCode = (String) this.getSessionMap().get("shopCode");
         
		        	taxList = GetListResource.GetTaxList(this.getSessionMap());
		        	unitList = GetListResource.GetUnitList();
		        	supplierList = GetListResource.GetSupplierList();
        	   
		        	String actualId = EncryptionDecryption.decrypt(this.getId());
        				Connection connection = null;
        		   		PreparedStatement preparedStatement= null;	
        		   		ResultSet resultSet = null;
        		   		
        		   		String sql = "";
        		   		String db = (String) session.getAttribute("db");
	        		   	
        		   		FileInputStream fis =  null;
	    				 
	     				if(getProductImage() != null )
	     				{
	     					fis =  new FileInputStream(getProductImage());
	     				}
        		   		
        		   		try
        		   		{
        		   			if(this.getDefaultBarCodeQty() == null || this.getDefaultBarCodeQty().equals("") || this.getDefaultBarCodeQty().equals(0.0F))
    						{
    							this.setDefaultBarCodeQty(1F);
    						}
    						if(this.getMrprate() == null || this.getMrprate().equals("") || this.getMrprate() == 0.0F)
    						{
    							this.setMrprate(this.getCustomerSalesRate());							
    						}
    						
    						if(this.getDiscount() == null || this.getDiscount().equals(""))
    						{
    							this.setDiscount(0.0F);
    						}
    						if(this.getDiscountType() == null || this.getDiscountType().equals(""))
    						{
    							this.setDiscountType("PERQUANTITY");
    						}
    						
    						if(this.getSalePrice() == null || this.getSalePrice().equals("") || this.getSalePrice() == 0.0F)
    						{
    							this.setSalePrice(this.getCustomerSalesRate());
    						}
    						
        		   			Map<String,String> taxInfo = GetListResource.GetTaxNamePercentage(this.getTaxId(), this.getSessionMap());
							Float taxPercantage = Float.parseFloat(taxInfo.get("TAX-PERCENTAGE"));
						
        		   			connection = GetDBConnection.getDBConnection(db);
        		   			connection.setAutoCommit(false);
        		   			if(getProductImage() == null)
    						{

        		   				sql = "UPDATE "
            		   					+ "shop_product_master "
            		   					+ "SET "
            		   					+ "product_short_code =?,"            		   					
            		   					+ "product_name_eng=?,"
            		   					+ "product_name_mar=?,"
            		   					+ "product_alias=?,"
            		   					+ "low_stock_count=?,"
            		   					+ "purchase_rate=?,"
            		   					+ "customer_sales_price=?,"
            		   					+ "dealer_sales_price=?,"
            		   					+ "retailer_sales_price=?,"
            		   					+ "tax_id=?,"
            		   					+ "tax_percentage=?,"
            		   					+ "purchase_unit=?,"
            		   					+ "sales_unit=?,"
            		   					+ "hsn_sac_code=?,"
            		   					+ "stock_conversion_ratio=?,"
            		   					+ "rack_number=?,"
            		   					+ "barcode_mrp=?,"
            		   					+ "discount_type=?,"
            		   					+ "discount_amount_percentage=?,"
            		   					+ "sales_price=?,"
            		   					+ "default_barcode_quantity=? "
            		   					+ "WHERE "
            		   					+ "product_id=? "
            		   					+ "AND "
            		   					+ "product_short_code = ? "
            		   					+ "AND "
            		   					+ "shop_id = ? "
            		   					+ "AND "
            		   					+ "shop_code = ? ";
        		   				
        		   				preparedStatement = connection.prepareStatement(sql);  
        		   				preparedStatement.setString(1, this.getProductCode());
        		   				preparedStatement.setString(2, this.getProductName());
        		   				preparedStatement.setString(3, this.getProductNameMarathi());
        		   				preparedStatement.setString(4, this.getAlias());
        		   				preparedStatement.setString(5, this.getLowStockCount());
        		   				preparedStatement.setFloat(6, this.getPuchaseRate());
        		   				preparedStatement.setFloat(7, this.getCustomerSalesRate());
        		   				preparedStatement.setFloat(8, this.getDealerSalesRate());
        		   				preparedStatement.setFloat(9, this.getRetailerSalesRate());
        		   				preparedStatement.setString(10, this.getTaxId());
        		   				preparedStatement.setFloat(11, taxPercantage);
        		   				preparedStatement.setString(12, this.getPurchaseUnit());
        		   				preparedStatement.setString(13, this.getSaleUnit());
        		   				preparedStatement.setString(14, this.getHsnCode());
        		   				preparedStatement.setString(15, this.getConvertQuantity());
        		   				preparedStatement.setString(16, this.getRackNumber());
        		   				preparedStatement.setFloat(17, this.getMrprate());
        		   				preparedStatement.setString(18, this.getDiscountType());
        		   				preparedStatement.setFloat(19, this.getDiscount());
        		   				preparedStatement.setFloat(20, this.getSalePrice());
        		   				preparedStatement.setFloat(21, this.getDefaultBarCodeQty());
        		   				preparedStatement.setString(22, actualId);
        		   				preparedStatement.setString(23, this.getProductCodeOld());
        		   				preparedStatement.setString(24, shopId);
        		   				preparedStatement.setString(25, shopCode);
        		   				
        		   				
    						}
        		   			else
        		   			{
        		   				sql = "UPDATE "
            		   					+ "shop_product_master "
            		   					+ "SET "   
            		   					+ "product_short_code =?," 
            		   					+ "product_name_eng=?,"
            		   					+ "product_name_mar=?,"
            		   					+ "product_alias=?,"
            		   					+ "low_stock_count=?,"
            		   					+ "purchase_rate=?,"
            		   					+ "customer_sales_price=?,"
            		   					+ "dealer_sales_price=?,"
            		   					+ "retailer_sales_price=?,"
            		   					+ "tax_id=?,"
            		   					+ "tax_percentage=?,"
            		   					+ "purchase_unit=?,"
            		   					+ "sales_unit=?,"
            		   					+ "hsn_sac_code=?,"
            		   					+ "stock_conversion_ratio=?,"
            		   					+ "rack_number=?,"
            		   					+ "product_image=?,"
            		   					+ "barcode_mrp=?,"
            		   					+ "discount_type=?,"
            		   					+ "discount_amount_percentage=?,"
            		   					+ "sales_price=?,"
            		   					+ "default_barcode_quantity=? "
            		   					+ "WHERE "
            		   					+ "product_id=? "
            		   					+ "AND "
            		   					+ "product_short_code = ? "
            		   					+ "AND "
            		   					+ "shop_id = ? "
            		   					+ "AND "
            		   					+ "shop_code = ? ";
        		   				
        		   				preparedStatement = connection.prepareStatement(sql);  
        		   				preparedStatement.setString(1, this.getProductCode());
        		   				preparedStatement.setString(2, this.getProductName());
        		   				preparedStatement.setString(3, this.getProductNameMarathi());
        		   				preparedStatement.setString(4, this.getAlias());
        		   				preparedStatement.setString(5, this.getLowStockCount());
        		   				preparedStatement.setFloat(6, this.getPuchaseRate());
        		   				preparedStatement.setFloat(7, this.getCustomerSalesRate());
        		   				preparedStatement.setFloat(8, this.getDealerSalesRate());
        		   				preparedStatement.setFloat(9, this.getRetailerSalesRate());
        		   				preparedStatement.setString(10, this.getTaxId());
        		   				preparedStatement.setFloat(11, taxPercantage);
        		   				preparedStatement.setString(12, this.getPurchaseUnit());
        		   				preparedStatement.setString(13, this.getSaleUnit());
        		   				preparedStatement.setString(14, this.getHsnCode());
        		   				preparedStatement.setString(15, this.getConvertQuantity());
        		   				preparedStatement.setString(16, this.getRackNumber());
        		   				preparedStatement.setBinaryStream(17, fis,(int)getProductImage().length());
        		   				preparedStatement.setFloat(18, this.getMrprate());
        		   				preparedStatement.setString(19, this.getDiscountType());
        		   				preparedStatement.setFloat(20, this.getDiscount());
        		   				preparedStatement.setFloat(21, this.getSalePrice());
        		   				preparedStatement.setFloat(22, this.getDefaultBarCodeQty());
        		   				preparedStatement.setString(23, actualId);
        		   				preparedStatement.setString(24, this.getProductCodeOld());
        		   				preparedStatement.setString(25, shopId);
        		   				preparedStatement.setString(26, shopCode);
        		   				
        		   		
        		   				
        		   				
        		   			}
        		   			int i = preparedStatement.executeUpdate();
    						
    						
    						if(i>0)
    						{
    								connection.commit();
    								result = SUCCESS;
        							addActionMessage("Product Details Updated Successfully !");	
    						
    							
    						}
    						else
    						{
    							result = "error";
    							addActionError("Product details not Updated !");
    						}
    								
        		   			
        		   		}catch (SQLException e) {
        		   			
        		   			//e.printStackTrace();
        		   			result = "error";
        					addActionError(e.getErrorCode()+" || "+e.getMessage()+"|| ERROR. Product details not Updated !");
        					
        					
        				} catch (IOException e) {
        					//e.printStackTrace();
        					result = "error";
        					addActionError(e.getMessage() +" || "+e.getCause()+"|| ERROR. Product details not Updated !");
        					
        				}	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) {
        						
        						}
        	    			}
        	    			
        	    			
        	    		}
        		   		if(fis != null)
        		   		{
        		   			try
        		   			{
        		   				fis.close();
        		   				fis = null;
        		   			}
        		   			catch(IOException ioe)
        		   			{
        		   				
        		   			}
        		   		}

        	}
        return result;
	}

	
	@Override
	public void validate() 
	{
		try {
			taxList = GetListResource.GetTaxList(this.getSessionMap());
			unitList = GetListResource.GetUnitList();
			supplierList = GetListResource.GetSupplierList();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	

		if(this.getProductName().equals("") || this.getProductNameMarathi().equals("" )
				|| this.getAlias().equals("") || this.getLowStockCount().equals("") 
				|| this.getTaxId().equals("") 
				|| this.getSaleUnit().equals("") || this.getPurchaseUnit().equals("") || this.getHsnCode().equals("") 
				|| this.getConvertQuantity().equals(""))
		{
			this.addActionError("Please provide details for fields marked with (*) astrick!");
		}
		
		if(!this.hasActionErrors())
		{
			if(this.getPuchaseRate() == null || this.getPuchaseRate().equals(""))
			{
				this.addActionError("Please provide correct purchase price!");
			}
		}
		
		if(!this.hasActionErrors())
		{
			if(this.getCustomerSalesRate() == null || this.getCustomerSalesRate().equals(""))
			{
				addActionError("Please provide correct customer sales price!");
			}
		}
		if(!this.hasActionErrors())
		{
			if(this.getRetailerSalesRate() == null || this.getRetailerSalesRate().equals(""))
			{
				addActionError("Please provide correct retailer sales price!");
			}
		}
		
		if(!hasActionErrors())
		{
			if(this.getDealerSalesRate() == null || this.getDealerSalesRate().equals(""))
			{
				addActionError("Please provide correct dealer sales price!");
			}
		}

		
		String condition = "and product_name_eng != '"+this.getProductName()+"'";
		if(!hasActionErrors())
		{
			String isAliasAdded = "false";
			
			String [] result = new String[2];
			
			result = new CheckAlreadyAvailable().checkAvaibility("shop_product_master", "product_name_eng", condition , getProductName(), this.getSessionMap());
			
			isAliasAdded = result[0];
			
			if(isAliasAdded.equals("true"))
			{
				addActionError("Product is already added with same name !");
			}				
			
		}
		String condition2 = "and product_name_mar != '"+getProductNameMarathi()+"'";
		if(!hasActionErrors())
		{
			String isAliasAdded = "false";
			
			String [] result = new String[2];
			
			result = new CheckAlreadyAvailable().checkAvaibility("shop_product_master", "product_name_mar", condition2, getProductNameMarathi(), this.getSessionMap());
			
			isAliasAdded = result[0];
			
			if(isAliasAdded.equals("true"))
			{
				addActionError("Product is already added with same marathi name !");
			}				
			
		}
		String condition3 = "and product_alias != '"+getAlias()+"'";
		if(!hasActionErrors())
		{
			String isAliasAdded = "false";
			
			String [] result = new String[2];
			
			result = new CheckAlreadyAvailable().checkAvaibility("shop_product_master", "product_alias", condition3, getAlias(), this.getSessionMap());
			
			isAliasAdded = result[0];
			
			if(isAliasAdded.equals("true"))
			{
				addActionError("Alias is Already Added !!!");
			}				
			
		}
		
		
		
		String condition4 = "and product_short_code != '"+this.getProductCode()+"'";
		if(!hasActionErrors())
		{
			String isAliasAdded = "false";
			
			String [] result = new String[2];
			
			result = new CheckAlreadyAvailable().checkAvaibility("shop_product_master", "product_short_code", condition4, this.getProductCode(), this.getSessionMap());
			
			isAliasAdded = result[0];
			
			if(isAliasAdded.equals("true"))
			{
				addActionError("Product Code is Already Added !!!");
			}				
			
		}
		
		
		
		if(!hasActionErrors())
		{
			try
			{
				Integer.parseInt(getLowStockCount());
			}
			catch(NumberFormatException nfe)
			{
				addActionError("Please provide correct low stock count !");
			}
		}
		
		
		
		this.getDiscountTypeList().put("PERCENTAGE", "PERCENTAGE");
    	this.getDiscountTypeList().put("PERQUANTITY", "PERQUANTITY");
		
	}
	

	public HttpSession getSession() {
		return session;
	}


	public void setSession(HttpSession session) {
		this.session = session;
	}


	public String getProductAddDate() {
		return productAddDate;
	}


	public void setProductAddDate(String productAddDate) {
		this.productAddDate = productAddDate;
	}


	public String getProductName() {
		return productName;
	}


	public void setProductName(String productName) {
		this.productName = productName;
	}



	public String getProductNameMarathi() {
		return productNameMarathi;
	}


	public void setProductNameMarathi(String productNameMarathi) {
		this.productNameMarathi = productNameMarathi;
	}



	public String getAlias() {
		return Alias;
	}


	public void setAlias(String alias) {
		Alias = alias;
	}


	public String getSaleUnit() {
		return saleUnit;
	}


	public void setSaleUnit(String saleUnit) {
		this.saleUnit = saleUnit;
	}


	public String getPurchaseUnit() {
		return purchaseUnit;
	}


	public void setPurchaseUnit(String purchaseUnit) {
		this.purchaseUnit = purchaseUnit;
	}


	public String getLowStockCount() {
		return lowStockCount;
	}


	public void setLowStockCount(String lowStockCount) {
		this.lowStockCount = lowStockCount;
	}


	public String getHsnCode() {
		return hsnCode;
	}


	public void setHsnCode(String hsnCode) {
		this.hsnCode = hsnCode;
	}


	public String getConvertQuantity() {
		return convertQuantity;
	}


	public void setConvertQuantity(String convertQuantity) {
		this.convertQuantity = convertQuantity;
	}


	public File getProductImage() {
		return productImage;
	}


	public void setProductImage(File productImage) {
		this.productImage = productImage;
	}


	public Map<String, String> getTaxList() {
		return taxList;
	}


	public void setTaxList(Map<String, String> taxList) {
		this.taxList = taxList;
	}


	public Map<String, String> getUnitList() {
		return unitList;
	}


	public void setUnitList(Map<String, String> unitList) {
		this.unitList = unitList;
	}


	public Map<String, String> getSupplierList() {
		return supplierList;
	}


	public void setSupplierList(Map<String, String> supplierList) {
		this.supplierList = supplierList;
	}



	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 getPuchaseRate() {
		return puchaseRate;
	}


	public void setPuchaseRate(Float puchaseRate) {
		this.puchaseRate = puchaseRate;
	}


	public String getProductCode() {
		return productCode;
	}


	public void setProductCode(String productCode) {
		this.productCode = productCode;
	}


	public Float getCustomerSalesRate() {
		return customerSalesRate;
	}


	public void setCustomerSalesRate(Float customerSalesRate) {
		this.customerSalesRate = customerSalesRate;
	}


	public Float getRetailerSalesRate() {
		return retailerSalesRate;
	}


	public void setRetailerSalesRate(Float retailerSalesRate) {
		this.retailerSalesRate = retailerSalesRate;
	}


	public Float getDealerSalesRate() {
		return dealerSalesRate;
	}


	public void setDealerSalesRate(Float dealerSalesRate) {
		this.dealerSalesRate = dealerSalesRate;
	}


	public String getRackNumber() {
		return rackNumber;
	}


	public void setRackNumber(String rackNumber) {
		this.rackNumber = rackNumber;
	}


	public String getTaxId() {
		return taxId;
	}


	public void setTaxId(String taxId) {
		this.taxId = taxId;
	}


	public String getId() {
		return id;
	}


	public void setId(String id) {
		this.id = id;
	}


	public static long getSerialversionuid() {
		return serialVersionUID;
	}


	public Map<String, String> getCustomerSearchOptionList() {
		return customerSearchOptionList;
	}


	public void setCustomerSearchOptionList(Map<String, String> customerSearchOptionList) {
		this.customerSearchOptionList = customerSearchOptionList;
	}


	public String getCustomerSearchOption() {
		return customerSearchOption;
	}


	public void setCustomerSearchOption(String customerSearchOption) {
		this.customerSearchOption = customerSearchOption;
	}


	public String getDefaultValue() {
		return defaultValue;
	}


	public void setDefaultValue(String defaultValue) {
		this.defaultValue = defaultValue;
	}


	public Map<String, String> getDiscountTypeList() {
		return discountTypeList;
	}


	public void setDiscountTypeList(Map<String, String> discountTypeList) {
		this.discountTypeList = discountTypeList;
	}


	public String getDiscountType() {
		return discountType;
	}


	public void setDiscountType(String discountType) {
		this.discountType = discountType;
	}


	public Float getDefaultBarCodeQty() {
		return defaultBarCodeQty;
	}


	public void setDefaultBarCodeQty(Float defaultBarCodeQty) {
		this.defaultBarCodeQty = defaultBarCodeQty;
	}


	public Float getMrprate() {
		return mrprate;
	}


	public void setMrprate(Float mrprate) {
		this.mrprate = mrprate;
	}


	public Float getDiscount() {
		return discount;
	}


	public void setDiscount(Float discount) {
		this.discount = discount;
	}


	public Float getSalePrice() {
		return salePrice;
	}


	public void setSalePrice(Float salePrice) {
		this.salePrice = salePrice;
	}


	public String getProductCodeOld() {
		return productCodeOld;
	}


	public void setProductCodeOld(String productCodeOld) {
		this.productCodeOld = productCodeOld;
	}


	
	
	
	
}