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.ArrayList;
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.TaxDAO;
import com.reallinkbilling.db.GetDBConnection;

public class AddNewTax extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 4108681230226340561L;
	private HttpSession session;
	private String taxName;
	private Float taxPercentage;
	private List<TaxDAO> taxList = new ArrayList<TaxDAO>();
	private SessionMap<String,Object> sessionMap;  
	
	
	
	@Override
	public String execute() throws Exception {
		
		String result = "login";
		session=ServletActionContext.getRequest().getSession(false); 
		 
	        if(session==null || session.getAttribute("login")==null){ 
	        	addActionMessage("Please Login First !!!");
	        	result = "login";
	        }  
	        else
	        {
	        	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);
					
					sql = "SELECT "
							+ "id_tax_table "
							+ "FROM "
							+ "shop_tax_table_master "
							+ "WHERE "
							+ "shop_id = ? "
							+ "AND "
							+ "shop_code = ? "
							+ "ORDER BY "
							+ "id_tax_table "
							+ "DESC LIMIT 1";
					
				
				preparedStatement = connection.prepareStatement(sql);
				preparedStatement.setString(1, shopId);
				preparedStatement.setString(2, shopCode);
				
				resultSet = preparedStatement.executeQuery();
					

					int newTaxId = 1;
					if(resultSet.next())
					{
						if(!(resultSet.getString(1) == null))
						{
							newTaxId = resultSet.getInt(1) + 1;
							
							
						}
						else
						{
							newTaxId =1;
							
							
						}
					}
					
					
					if(resultSet != null)
					{
						resultSet.close();
						resultSet = null;
					
					}
					if(preparedStatement != null)
					{
						preparedStatement.close();
						preparedStatement = null;
					}
					
					sql = "INSERT INTO "
							+ "shop_tax_table_master "
							+ "("
							+ "id_tax_table,"
							+ "shop_id,"
							+ "shop_code,"
							+ "tax_name,"
							+ "taxpercentage) "
							+ "VALUES (?,?,?,?,?)";
					
					preparedStatement = connection.prepareStatement(sql);
					preparedStatement.setInt(1, newTaxId);
					preparedStatement.setString(2, shopId);
					preparedStatement.setString(3, shopCode);
					preparedStatement.setString(4, this.getTaxName());
					preparedStatement.setFloat(5, this.getTaxPercentage());
					
					int i = preparedStatement.executeUpdate();
				
					
					
					if(i>0)
					{
						if(preparedStatement != null)
						{
							preparedStatement.close();
							preparedStatement = null;
						}
						
						sql = "SELECT "
								+ "tax_name,"
								+ "taxpercentage "
								+ "FROM "
								+ "shop_tax_table_master "
								+ "WHERE "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? "
								+ "ORDER BY "
								+ "taxpercentage";
						
						preparedStatement = connection.prepareStatement(sql);
						preparedStatement.setString(1, shopId);
						preparedStatement.setString(2, shopCode);
						
						resultSet = preparedStatement.executeQuery();
						
						int serial = 1;
						
						while(resultSet.next())
						{
							TaxDAO taxDAO = new TaxDAO();
							taxDAO.setSerial(""+serial);
							taxDAO.setTaxName(resultSet.getString(1));
							taxDAO.setTaxPercentage(resultSet.getFloat(2));
							this.getTaxList().add(taxDAO);
							serial++;
						}
						result= SUCCESS;
						addActionMessage("New TAX Added Successfully !");
					}
					else
					{
						result= ERROR;
						addActionError("TAX not added !");
					}
					
				} catch (SQLException e) {
					result = ERROR;
					
					addActionError(e.getErrorCode()+" || "+e.getMessage() +" || TAX Not Added !!!");
				} catch (IOException e) {
					result = ERROR;
					
					addActionError(e.getMessage()+" || "+e.getCause()+" || TAX Not Added !!!");
				}finally {
					if(resultSet != null)
					{
						resultSet.close();
						resultSet = null;
					}
					if(preparedStatement != null)
					{
						try {preparedStatement.close();
						preparedStatement = null;
						} catch (SQLException e) {}
					}
					if(connection != null)
					{
						
						try {connection.close();
						connection = null;}catch (SQLException e) {}
					}
					
				}
	        	
	        }
		
		return result;
	}
	
	
	@Override
	public void validate() {
		
		String shopId = (String) this.getSessionMap().get("shopId");
		String shopCode = (String) this.getSessionMap().get("shopCode");
		
		
		
		if(this.getTaxName() ==null || getTaxName().equals(""))
		{
			addActionError("Please provide TAX Name !");
		}
		
		
		
		if(!hasActionErrors())
		{
			
			if(this.getTaxPercentage() ==null || this.getTaxPercentage().equals(""))
			{
				addActionError("Please provide appropriate percentage value !");
			}
		}
		
		if(!hasActionErrors())
		{
			Connection connection = null;
			PreparedStatement preparedStatement= null;
			ResultSet resultSet = null;
			
			String sql = "";
			String db = (String) this.getSessionMap().get("db");
			
			try
			{
				
				connection = GetDBConnection.getDBConnection(db);
				sql = "SELECT * "
						+ "FROM shop_tax_table_master "
						+ "WHERE "
						+ "tax_name=? "
						+ "AND "
						+ "taxpercentage =? "
						+ "AND "
						+ "shop_id = ? "
						+ "AND "
						+ "shop_code = ? ";
				
				
				preparedStatement = connection.prepareStatement(sql);
				
				preparedStatement.setString(1, getTaxName());
				preparedStatement.setFloat(2, getTaxPercentage());
				preparedStatement.setString(3, shopId);
				preparedStatement.setString(4, shopCode);
				
				resultSet = preparedStatement.executeQuery();
				
				
				if(resultSet.next())
				{
					
					addActionError(getTaxName()+" is already added !");
					this.setTaxName("");
					this.setTaxPercentage(0.0F);
				}
				
			} catch (SQLException e) {
				
				addActionError(e.getErrorCode()+" || "+e.getMessage());
			} catch (IOException e) {
				
				addActionError(e.getMessage()+" || "+e.getCause());
			}finally {
				if(resultSet != null)
   				{
   					try {resultSet.close();}catch(SQLException sqe){}   					
   				}
				if(preparedStatement != null)
				{
					try {preparedStatement.close();} catch (SQLException e) {}
				}
				if(connection != null)
				{
					
					try {connection.close();}catch (SQLException e) {}
				}
				
			}
		}
		
	}
	public HttpSession getSession() {
		return session;
	}
	public void setSession(HttpSession session) {
		this.session = session;
	}
	public String getTaxName() {
		return taxName;
	}
	public void setTaxName(String taxName) {
		this.taxName = taxName;
	}
	
	public Float getTaxPercentage() {
		return taxPercentage;
	}

	public void setTaxPercentage(Float taxPercentage) {
		this.taxPercentage = taxPercentage;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public List<TaxDAO> getTaxList() {
		return taxList;
	}
	public void setTaxList(List<TaxDAO> taxList) {
		this.taxList = taxList;
	}

	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;  
	}
	
	
}
