package com.reallinkbilling.add;

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.text.SimpleDateFormat;
import java.util.Date;
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.DAO.ProductBarcodeDetailsDAO;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.CheckAlreadyAvailable;
import com.reallinkbilling.resource.GetListResource;

public class AddNewProductPanel extends ActionSupport implements SessionAware{

	
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -179420354938902915L;

	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 Float initialStock;
	private File productImage;
	private String key;
	
	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> 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;
	
	
	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{
	        	Date d = new Date();
	        	SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
	        	this.setProductAddDate(dateFormat.format(d));
	        	
	        	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");
				FileInputStream fis =  null;
				
				
			
					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());
						}
						
						
						connection = GetDBConnection.getDBConnection(db);		
						
						
						sql = "SELECT "
								+ "product_id "
								+ "FROM "
								+ "shop_product_master "
								+ "WHERE "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? "
								+ "ORDER BY "
								+ "product_id "
								+ "DESC LIMIT 1";
						
					
					preparedStatement = connection.prepareStatement(sql);
					preparedStatement.setString(1, shopId);
					preparedStatement.setString(2, shopCode);
					
					resultSet = preparedStatement.executeQuery();
						

						int newProductId = 1;
						if(resultSet.next())
						{
							if(!(resultSet.getString(1) == null))
							{
								newProductId = resultSet.getInt(1) + 1;
								
								
							}
							
						}
						
						
						if(resultSet != null)
						{
							resultSet.close();
							resultSet = null;
						
						}
						if(preparedStatement != null)
						{
							preparedStatement.close();
							preparedStatement = null;
						}
						
						
						

						
						this.setTaxList(GetListResource.GetTaxList(this.getSessionMap()));
						unitList = GetListResource.GetUnitList();
						
						Map<String,String> taxInfo = GetListResource.GetTaxNamePercentage(this.getTaxId(), this.getSessionMap());
						Float taxPercantage = Float.parseFloat(taxInfo.get("TAX-PERCENTAGE"));
					
						if(this.getProductImage() != null)
						{
							fis = new FileInputStream(this.getProductImage());
							
						sql = "INSERT "
								+ "INTO "
								+ "shop_product_master "
								+ "("
								+ "product_id,"
								+ "shop_id,"
								+ "shop_code,"
								+ "add_date,"
								+ "product_name_eng,"
								+ "product_name_mar,"
								+ "product_short_code,"
								+ "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,"
								+ "product_image,"
								+ "in_stock_quantity,"
								+ "rack_number,"
								+ "barcode_mrp,"
								+ "discount_type,"
								+ "discount_amount_percentage,"
								+ "sales_price,"
								+ "default_barcode_quantity) "
								+ "values "
								+ "(?,?,?,STR_TO_DATE(?, '%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
						
								preparedStatement = connection.prepareStatement(sql);
								preparedStatement.setInt(1, newProductId);
								preparedStatement.setString(2, shopId);
								preparedStatement.setString(3, shopCode);
								preparedStatement.setString(4, this.getProductAddDate());
								preparedStatement.setString(5, this.getProductName().toUpperCase().trim());
								preparedStatement.setString(6, this.getProductNameMarathi().trim());
								preparedStatement.setString(7, this.getProductCode().toUpperCase().trim());
								preparedStatement.setString(8, this.getAlias().toUpperCase().trim());
								preparedStatement.setString(9, this.getLowStockCount());
								preparedStatement.setFloat(10, this.getPuchaseRate());
								preparedStatement.setFloat(11, this.getCustomerSalesRate());
								preparedStatement.setFloat(12, this.getDealerSalesRate());
								preparedStatement.setFloat(13, this.getRetailerSalesRate());
								preparedStatement.setString(14, this.getTaxId());
								preparedStatement.setFloat(15, taxPercantage);
								preparedStatement.setString(16, this.getPurchaseUnit());
								preparedStatement.setString(17, this.getSaleUnit());
								preparedStatement.setString(18, this.getHsnCode());
								preparedStatement.setString(19, this.getConvertQuantity());
								preparedStatement.setBinaryStream(20, fis,(int)getProductImage().length());
								preparedStatement.setFloat(21, this.getInitialStock());
								preparedStatement.setString(22, this.getRackNumber().toUpperCase().trim());
								preparedStatement.setFloat(23, this.getMrprate());
								preparedStatement.setString(24, this.getDiscountType());
								preparedStatement.setFloat(25, this.getDiscount());
								preparedStatement.setFloat(26, this.getSalePrice());
								preparedStatement.setFloat(27, this.getDefaultBarCodeQty());
								
						}
						if(getProductImage() == null)
						{
							//System.out.print("Hello in insert");
							
							
							sql = "INSERT "
									+ "INTO "
									+ "shop_product_master "
									+ "("
									+ "product_id,"
									+ "shop_id,"
									+ "shop_code,"
									+ "add_date,"
									+ "product_name_eng,"
									+ "product_name_mar,"
									+ "product_short_code,"
									+ "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,"
									+ "product_image,"
									+ "in_stock_quantity,"
									+ "rack_number,"
									+ "barcode_mrp,"
									+ "discount_type,"
									+ "discount_amount_percentage,"
									+ "sales_price,"
									+ "default_barcode_quantity) "
									+ "values "
									+ "(?,?,?,STR_TO_DATE(?, '%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
							
									
										preparedStatement = connection.prepareStatement(sql);
									preparedStatement.setInt(1, newProductId);
									preparedStatement.setString(2, shopId);
									preparedStatement.setString(3, shopCode);
									preparedStatement.setString(4, this.getProductAddDate());
									preparedStatement.setString(5, this.getProductName().toUpperCase().trim());
									preparedStatement.setString(6, this.getProductNameMarathi().trim());
									preparedStatement.setString(7, this.getProductCode().toUpperCase().trim());
									preparedStatement.setString(8, this.getAlias().toUpperCase().trim());
									preparedStatement.setString(9, this.getLowStockCount());
									preparedStatement.setFloat(10, this.getPuchaseRate());
									preparedStatement.setFloat(11, this.getCustomerSalesRate());
									preparedStatement.setFloat(12, this.getDealerSalesRate());
									preparedStatement.setFloat(13, this.getRetailerSalesRate());
									preparedStatement.setString(14, this.getTaxId());
									preparedStatement.setFloat(15, taxPercantage);
									preparedStatement.setString(16, this.getPurchaseUnit());
									preparedStatement.setString(17, this.getSaleUnit());
									preparedStatement.setString(18, this.getHsnCode());
									preparedStatement.setString(19, this.getConvertQuantity());
									preparedStatement.setBinaryStream(20, null);
									preparedStatement.setFloat(21, this.getInitialStock());
									preparedStatement.setString(22, this.getRackNumber().toUpperCase().trim());
									preparedStatement.setFloat(23, this.getMrprate());
									preparedStatement.setString(24, this.getDiscountType());
									preparedStatement.setFloat(25, this.getDiscount());
									preparedStatement.setFloat(26, this.getSalePrice());
									preparedStatement.setFloat(27, this.getDefaultBarCodeQty());
									
						}
						
						
						
						
						int i = preparedStatement.executeUpdate();
								
						
								if(i>0)
								{
									
									
									@SuppressWarnings("unchecked")
									Map<String,ProductBarcodeDetailsDAO> barcodeDetailsMap = (Map<String,ProductBarcodeDetailsDAO>) this.getSessionMap().get("barcodeProductDetails");
									if (barcodeDetailsMap == null) {
										barcodeDetailsMap = new HashMap<String, ProductBarcodeDetailsDAO>();
									}
									
									ProductBarcodeDetailsDAO  detailsDAO = new ProductBarcodeDetailsDAO();
									 detailsDAO.setProductId(""+newProductId);
									 detailsDAO.setProductCode(this.getProductCode().toUpperCase().trim());
									 detailsDAO.setProductNameEn(this.getProductName().toUpperCase().trim());
									 detailsDAO.setProductNameMr(this.getProductNameMarathi().trim());
									 detailsDAO.setTaxId(Integer.parseInt(this.getTaxId()));
									 detailsDAO.setTaxPercentage(taxPercantage);
									 detailsDAO.setSalesUnit(this.getSaleUnit());
									 detailsDAO.setHsnSacCode(this.getHsnCode());
									 detailsDAO.setBarcodeMRP(this.getMrprate());
									 detailsDAO.setDiscountType(this.getDiscountType());
									 detailsDAO.setDiscount(this.getDiscount());
									 detailsDAO.setSalesPrice(this.getSalePrice());
									 detailsDAO.setBarCodeQuantity(this.getDefaultBarCodeQty());
									 detailsDAO.setProductAlias(this.getAlias() != null ? this.getAlias().toUpperCase().trim() : "NA");
									 if (this.getInitialStock() != null) {
										 detailsDAO.setInStockQuantity(this.getInitialStock());
									 } else {
										 detailsDAO.setInStockQuantity(0F);
									 }
									 detailsDAO.setInStockQuantity2(0F);
									 detailsDAO.setPurchasePrice(this.getPuchaseRate());
									 detailsDAO.setCustomerSalePrice(this.getCustomerSalesRate());
									 
									 barcodeDetailsMap.put(this.getProductCode().toUpperCase().trim(), detailsDAO);
									
									 this.getSessionMap().put("barcodeProductDetails", barcodeDetailsMap);
										
									result = SUCCESS;
									addActionMessage("Product details added successfully !!!");
								}
								else
								{
									addActionError("Product details not added ! Please try again !!!");
									result=ERROR;
								}
						
								
					
	    	} catch (SQLException e) {
				result = "error";
				//e.printStackTrace();
				addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Product details not added ! Please try again !!!");
			} catch (IOException e) {
				result = "error";
				//e.printStackTrace();
				addActionError(e.getMessage()+" || "+e.getCause()+" || Product details not added ! Please try again !!!");
			}finally {

				if(fis != null)
	        	{
	        		fis.close();
	        	}
				
				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;
	}


	@Override
	public void validate() 
	{
	
			this.setTaxList(GetListResource.GetTaxList(this.getSessionMap()));
			this.setUnitList(GetListResource.GetUnitList());
		
    	
    	
		if(getProductName().equals("") || getProductNameMarathi().equals("" )
				|| getAlias().equals("") || getLowStockCount().equals("") 
				|| getTaxId().equals("") 
				|| getSaleUnit().equals("") || getPurchaseUnit().equals("") || getHsnCode().equals("") 
				|| getConvertQuantity().equals(""))
		{
			addActionError("Please provide details for fields marked with (*) astrick!");
		}
		
		if(!hasActionErrors())
		{
			if(this.getPuchaseRate() == null || this.getPuchaseRate().equals(""))
			{
				addActionError("Please provide correct purchase price!");
			}
		}
		
		if(!hasActionErrors())
		{
			if(this.getCustomerSalesRate() == null || this.getCustomerSalesRate().equals(""))
			{
				addActionError("Please provide correct customer sales price!");
			}
		}
		if(!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!");
			}
		}

		if(!hasActionErrors())
		{
			String isAliasAdded = "false";
			
			String [] result = new String[2];
			
			result = new CheckAlreadyAvailable().checkAvaibility("shop_product_master", "product_short_code", "NA", this.getProductCode(), this.getSessionMap());
			
			isAliasAdded = result[0];
			
			if(isAliasAdded.equals("true"))
			{
				addActionError("Product with this product Code is Already Added !!!");
			}				
			
		}
		
		if(!hasActionErrors())
		{
			String isAliasAdded = "false";
			
			String [] result = new String[2];
			
			result = new CheckAlreadyAvailable().checkAvaibility("shop_product_master", "product_name_eng", "NA", this.getProductName(), this.getSessionMap());
			
			isAliasAdded = result[0];
			
			if(isAliasAdded.equals("true"))
			{
				addActionError("Product is already added with same name !");
			}				
			
		}
		
		if(!hasActionErrors())
		{
			String isAliasAdded = "false";
			
			String [] result = new String[2];
			
			result = new CheckAlreadyAvailable().checkAvaibility("shop_product_master", "product_name_mar", "NA", this.getProductNameMarathi(), this.getSessionMap());
			
			isAliasAdded = result[0];
			
			if(isAliasAdded.equals("true"))
			{
				addActionError("Product is already added with same marathi name !");
			}				
			
		}
		
		if(!hasActionErrors())
		{
			String isAliasAdded = "false";
			
			String [] result = new String[2];
			
			result = new CheckAlreadyAvailable().checkAvaibility("shop_product_master", "product_alias", "NA", this.getAlias(), this.getSessionMap());
			
			isAliasAdded = result[0];
			
			if(isAliasAdded.equals("true"))
			{
				addActionError("Alias is Already Added !!!");
			}				
			
		}
		
		
		if(!hasActionErrors())
		{
			try
			{
				Integer.parseInt(this.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 Float getPuchaseRate() {
		return puchaseRate;
	}


	public void setPuchaseRate(Float puchaseRate) {
		this.puchaseRate = puchaseRate;
	}


	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 static long getSerialversionuid() {
		return serialVersionUID;
	}


	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 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 String getLowStockCount() {
		return lowStockCount;
	}



	public void setLowStockCount(String lowStockCount) {
		this.lowStockCount = lowStockCount;
	}



	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 File getProductImage() {
		return productImage;
	}


	public void setProductImage(File productImage) {
		this.productImage = productImage;
	}


	public String getKey() {
		return key;
	}


	public void setKey(String key) {
		this.key = key;
	}


	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 String getProductCode() {
		return productCode;
	}


	public void setProductCode(String productCode) {
		this.productCode = productCode;
	}


	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 Float getInitialStock() {
		return initialStock;
	}


	public void setInitialStock(Float initialStock) {
		this.initialStock = initialStock;
	}
		
	
	
	
	
	

}
