package com.reallinkbilling.ajax;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
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.BillProductInfoDAO;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.GetListResource;

public class GetAliasFullName extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 6993409795460783076L;
	private String fullName;
	private String aliasValue;
	private String fullNameMarathi;
	private String salesUnit;
	private String tax;
	private String salesRate;
	private HttpSession session;
	private String customerName;
	private String inStockQty;
	
	private SessionMap<String,Object> sessionMap;  
	private Boolean showAlertMessageForChangeInGSTCode;
	private String alertMessageForChangeInGSTCode;
	
	@Override
	synchronized 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{
		        	
		        	
		        	DecimalFormat df = new DecimalFormat("##.##");
		        	
		        	String custData [] = new String [5];
		        	try
		        	{
		        		
		        		custData = this.getCustomerName().split("-");
		        	}
		        	catch(Exception e)
		        	{
		        		custData[0] = "1";
		        		custData[1] = this.getCustomerName().trim().toUpperCase();
		        		custData[2] = "9999999999";
		        		custData[3] = "REGULER";
		        		
		        		e.printStackTrace();
		        	}
		       
		        	String custType = "";
		        	String shopId = (String) this.getSessionMap().get("shopId");
		    		String shopCode = (String) this.getSessionMap().get("shopCode");
		    		String [] productData = new String [3];
		    	     
		    		String prName = "";
		    		String prId = "";
		    		String prAlias = "";
		    		try
		    		{
		    			custType = custData[3];
		    			String aliasInput = this.getAliasValue() == null ? "" : this.getAliasValue().trim();
		    			productData = aliasInput.split("-");
		    			if(productData.length >= 3)
		    			{
		    				prId =  productData[0].trim().toUpperCase();
		    				prName = productData[1].trim().toUpperCase();
		    				prAlias = productData[2].trim().toUpperCase();
		    			}
		    			else
		    			{
		    				prAlias = aliasInput.toUpperCase();
		    				prName = aliasInput.toUpperCase();
		    			}
		    			
		    		}catch(Exception e)
		    		{
		    			e.printStackTrace();
		    			String aliasInput = this.getAliasValue() == null ? "" : this.getAliasValue().trim();
		    			prAlias = aliasInput.toUpperCase();
		    			prName = aliasInput.toUpperCase();
		    		}
		    	
		        	
		        	Connection connection = null;
					PreparedStatement preparedStatement= null;
					ResultSet resultSet = null;
					
					String sql = "";
					String db = (String) this.getSessionMap().get("db");
					
			
					try
					{
						connection = GetDBConnection.getDBConnection(db);
						
						String custGSTNum = "";
						String ownGSTNum = (String) this.getSessionMap().get("shopgstnumber");
						
						boolean isCustGSTOtherState = false;
						
						if(ownGSTNum != null || !ownGSTNum.equals("NA") || !ownGSTNum.equals(""))
						{
						
						sql = "SELECT "
								+ "gst_number "
								+ "FROM "
								+ "shop_customer_master "
								+ "WHERE "
								+ "customer_id = ? "
								+ "AND "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? ";
						
						preparedStatement = connection.prepareStatement(sql);
						
						preparedStatement.setString(1, custData[0]);
						preparedStatement.setString(2, shopId);
						preparedStatement.setString(3, shopCode);
						
						resultSet = preparedStatement.executeQuery();
						
						if(resultSet.next())
						{
							custGSTNum = resultSet.getString(1);
						}
						else
						{
							custGSTNum = "NA";
						}
						
						
						String gstStateCode= ownGSTNum.substring(0,2);
					
						if(!custGSTNum.equals("NA") || !custGSTNum.equals(""))
						{
							if(custGSTNum.length() > 2)
							{
								String custStateCode = custGSTNum.substring(0,2);
								
							if(!custStateCode.equals(gstStateCode))
								{
									isCustGSTOtherState = true;
									
										List <BillProductInfoDAO> proList =	(List<BillProductInfoDAO>) this.getSessionMap().get("productList");
										
										if(proList == null)
										{
											this.setShowAlertMessageForChangeInGSTCode(true);
											this.setAlertMessageForChangeInGSTCode("State GST Code of customer is different. Hence setting to IGST!");
										}
								}
							}
						}
						
						if(resultSet != null)
						{
							resultSet.close();
							resultSet = null;
						}
							
						if(preparedStatement != null)
						{
							preparedStatement.close();
							preparedStatement = null;
						}
						}
						
						if(custType.equals("REGULER"))
						{
							sql = "SELECT "
									+ "product_id,"
									+ "product_name_eng,"
									+ "product_name_mar,"
									+ "sales_unit,"
									+ "tax_id,"
									+ "customer_sales_price,"
									+ "product_short_code,"
									+ "in_stock_quantity "
									+ "FROM "
									+ "shop_product_master "
									+ "WHERE "
									+ "shop_id = ? "
									+ "AND "
									+ "shop_code = ? "
									+ "AND "
									+ "(product_alias = '"+prAlias+"' "
											+ "OR product_name_eng='"+prName+"')";
						}
						if(custType.equals("DEALER"))
						{
							sql = "SELECT "
									+ "product_id,"
									+ "product_name_eng,"
									+ "product_name_mar,"
									+ "sales_unit,"
									+ "tax_id,"
									+ "dealer_sales_price,"
									+ "product_short_code,"
									+ "in_stock_quantity "
									+ "FROM "
									+ "shop_product_master "
									+ "WHERE "
									+ "shop_id = ? "
									+ "AND "
									+ "shop_code = ? "
									+ "AND "
									+ "(product_alias = '"+prAlias+"' "
									+ "OR product_name_eng='"+prName+"')";
						}
						if(custType.equals("RETAILER"))
						{
							sql = "SELECT "
									+ "product_id,"
									+ "product_name_eng,"
									+ "product_name_mar,"
									+ "sales_unit,"
									+ "tax_id,"
									+ "retailer_sales_price,"
									+ "product_short_code,"
									+ "in_stock_quantity "
									+ "FROM "
									+ "shop_product_master "
									+ "WHERE "
									+ "shop_id = ? "
									+ "AND "
									+ "shop_code = ? "
									+ "AND "
									+ "(product_alias = '"+prAlias+"' "
									+ "OR product_name_eng ='"+prName+"')";
									
						}	
							
							
							preparedStatement = connection.prepareStatement(sql);
							preparedStatement.setString(1, shopId);
							preparedStatement.setString(2, shopCode);
							resultSet = preparedStatement.executeQuery();
				
							resultSet.last();
							int rowCount = resultSet.getRow();
							resultSet.beforeFirst();
			
							if(rowCount>0)
							{
								if(isCustGSTOtherState)
								{
							
									while(resultSet.next())
									{
										this.setFullName(resultSet.getString(1)+"-"+resultSet.getString(2)+"-"+resultSet.getString(7));
										this.setFullNameMarathi(resultSet.getString(3));
										this.setSalesUnit(resultSet.getString(4));								
										this.setSalesRate(resultSet.getString(6));
										this.setInStockQty(df.format(resultSet.getFloat(8)));
										
										Map<String,String> taxInfo = GetListResource.GetTaxNamePercentage(resultSet.getString(5),this.getSessionMap());
									    
										Map<String,String> taxList = (Map<String, String>) this.getSessionMap().get("tax_list");
										
										String taxName = taxInfo.get("TAX-NAME");
										String taxPercentage = taxInfo.get("TAX-PERCENTAGE");
										
										
										
										int taxPercentageInt = Integer.parseInt(taxPercentage);
										
										if(taxPercentageInt > 0)
										{
										
										for(String key : taxList.keySet())
										{
											String taxNameIn = taxList.get(key);
											if(taxNameIn.equals("IGST-"+taxPercentageInt))
											{
												this.setTax(key);
											}
										}
										}
										else
										{
											this.setTax(resultSet.getString(5));
										}
										
										
										
										
									}
								}
								else
								{
								
									while(resultSet.next())
									{
										this.setFullName(resultSet.getString(1)+"-"+resultSet.getString(2)+"-"+resultSet.getString(7));
										this.setFullNameMarathi(resultSet.getString(3));
										this.setSalesUnit(resultSet.getString(4));								
										this.setTax(resultSet.getString(5));
										this.setSalesRate(resultSet.getString(6));
										this.setInStockQty(df.format(resultSet.getFloat(8)));
									}
								}
								result = SUCCESS;
							}
							else
							{
								result = ERROR;
							}
							
						}catch (SQLException e) {
							result = ERROR;
							e.printStackTrace();
						} catch (IOException e) {
							result = ERROR;
							e.printStackTrace();
						}catch (Exception e) {
							result = ERROR;
							e.printStackTrace();
						}finally {
							if(resultSet != null)
			   				{
			   					try {resultSet.close(); resultSet = null;}catch(SQLException sqe) {}   					
			   				}
							if(preparedStatement != null)
							{
								try {preparedStatement.close(); resultSet = null;} catch (SQLException e) {}
							}
							if(connection != null)
							{
								
								try {connection.close(); connection = null;}catch (SQLException e) {}
							}
							
						}
		        }
		
		return result;
	}
	public String getAliasValue() {
		return aliasValue;
	}
	public void setAliasValue(String aliasValue) {
		this.aliasValue = aliasValue;
	}
	public String getFullName() {
		return fullName;
	}
	public void setFullName(String fullName) {
		this.fullName = fullName;
	}
	public String getFullNameMarathi() {
		return fullNameMarathi;
	}
	public void setFullNameMarathi(String fullNameMarathi) {
		this.fullNameMarathi = fullNameMarathi;
	}
	public String getSalesUnit() {
		return salesUnit;
	}
	public void setSalesUnit(String salesUnit) {
		this.salesUnit = salesUnit;
	}
	public String getTax() {
		return tax;
	}
	public void setTax(String tax) {
		this.tax = tax;
	}
	public String getSalesRate() {
		return salesRate;
	}
	public void setSalesRate(String salesRate) {
		this.salesRate = salesRate;
	}
	public String getCustomerName() {
		return customerName;
	}
	public void setCustomerName(String customerName) {
		this.customerName = customerName;
	}
	

	public String getInStockQty() {
		return inStockQty;
	}
	public void setInStockQty(String inStockQty) {
		this.inStockQty = inStockQty;
	}
	
	
	public Boolean getShowAlertMessageForChangeInGSTCode() {
		return showAlertMessageForChangeInGSTCode;
	}
	public void setShowAlertMessageForChangeInGSTCode(Boolean showAlertMessageForChangeInGSTCode) {
		this.showAlertMessageForChangeInGSTCode = showAlertMessageForChangeInGSTCode;
	}
	public String getAlertMessageForChangeInGSTCode() {
		return alertMessageForChangeInGSTCode;
	}
	public void setAlertMessageForChangeInGSTCode(String alertMessageForChangeInGSTCode) {
		this.alertMessageForChangeInGSTCode = alertMessageForChangeInGSTCode;
	}
	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;  
	}


	
	
	
}
