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;

public class AddNewBankAccount extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 2817788565235865992L;
	
	private HttpSession session;
	private String accountHolderName;
	private String accountNumber;
	private String ifscCode;
	private String bankName;
	private String branch;
	private Float openingBalance;
	
	private Map<String,String> customerSearchOptionList = new HashMap<String,String>();
	private String customerSearchOption;
	private String defaultValue;
	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");
				
				String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
					try
					{
						
			    		
						connection = GetDBConnection.getDBConnection(db);
						
						
						sql = "SELECT "
								+ "account_id "
								+ "FROM "
								+ "bank_account "						
								+ "WHERE "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? "
								+ "ORDER BY "
								+ "account_id "
								+ "DESC LIMIT 1";
						
					
					preparedStatement = connection.prepareStatement(sql);
					preparedStatement.setString(1, shopId);
					preparedStatement.setString(2, shopCode);
					
					resultSet = preparedStatement.executeQuery();
					
					int accountId = 1;
				
					if(resultSet.next())
					{
						if(!(resultSet.getString(1) == null))
						{
							accountId = Integer.parseInt(resultSet.getString(1));
							accountId = accountId + 1;
							
						}
						
					}
					else
					{	accountId =1;
						
					}
					
	        		if(resultSet != null)
	        		{
	        			resultSet.close();
	        			resultSet = null;
	        		}
	        		if(preparedStatement!= null)
	        		{
	        			preparedStatement.close();
	        			preparedStatement = null;
	        		}
						
						sql = "INSERT "
								+ "INTO "
								+ "bank_account "
								+ "("
								+ "shop_id,"
								+ "shop_code,"
								+ "account_id,"
								+ "account_holder_name,"
								+ "account_number,"
								+ "ifsc_code,"
								+ "bank_name,"
								+ "branch,"
								+ "opening_balance) "
								+ "VALUES "
								+ "(?,?,?,?,?,?,?,?,?)";
						
						preparedStatement = connection.prepareStatement(sql);
						preparedStatement.setString(1, shopId);
						preparedStatement.setString(2, shopCode);
						preparedStatement.setInt(3, accountId);
						preparedStatement.setString(4, this.getAccountHolderName().trim().toUpperCase());
						preparedStatement.setString(5, this.getAccountNumber().trim().toUpperCase());
						preparedStatement.setString(6, this.getIfscCode().trim().toUpperCase());
						preparedStatement.setString(7, this.getBankName());
						preparedStatement.setString(8, this.getBranch());
						preparedStatement.setFloat(9, this.getOpeningBalance());
						
						int k = preparedStatement.executeUpdate();
						
						if(k>0)
						{
							result = SUCCESS;
							addActionMessage("Account details added successfully!");
						}
						else
						{
							result = ERROR;
							addActionError("Sorry! Account details not added! Please try again!");
						}
					}catch (SQLException e) {
						
						result = ERROR;					
						addActionError(e.getErrorCode()+" || "+e.getMessage() +" || Bank details not added !");
					
					} catch (IOException e) {
						
						result = ERROR;				
						addActionError(e.getMessage()+" || "+e.getCause()+" || Bank details not added !");
					
					}finally {
						if(resultSet != null)
						{
							try{
								resultSet.close();
								resultSet = null;
							}catch(Exception e){}
									
						}
						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() {

			if(this.getAccountHolderName() == null || this.getAccountHolderName().equals(""))
			{
				addActionMessage("Please provide account holder name!");
			}
			
			if(!hasActionErrors())
			{
				if(this.getAccountNumber() == null || this.getAccountNumber().equals(""))
				{
					addActionError("Please provide account number!");
				}else if(this.getAccountNumber().length() > 40)
				{
					addActionError("Please provide correct account number!");
				}
					
			}
			
			if(!hasActionErrors())
			{
				if(this.getIfscCode() == null || this.getIfscCode().equals(""))
				{
					addActionError("Please provide IFSC code!");
				}
			}
			
			if(!hasActionErrors())
			{
				if(this.getBankName() == null || this.getBankName().equals(""))
				{
					addActionError("Please provide name of the bank!");
				}
			}
			
			if(!hasActionErrors())
			{
				if(this.getBranch() == null || this.getBranch().equals(""))
				{
					addActionError("Please provide branch!");
				}
			}
			
			if(!hasActionErrors())
			{
				if(this.getOpeningBalance() == null || this.getOpeningBalance().equals(""))
				{
					addActionError("Please provide correct opening balance amount!");
				}
			}
			
			

			customerSearchOptionList.put("BYNAME", "BY NAME");
        	customerSearchOptionList.put("BYMOBILE", "BY MOBILE");
        	customerSearchOptionList.put("BYADDRESS","BY ADDRESS");
			this.setCustomerSearchOption("BYNAME");
			this.setDefaultValue("BYNAME");
			
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public String getAccountHolderName() {
		return accountHolderName;
	}

	public void setAccountHolderName(String accountHolderName) {
		this.accountHolderName = accountHolderName;
	}

	public String getAccountNumber() {
		return accountNumber;
	}

	public void setAccountNumber(String accountNumber) {
		this.accountNumber = accountNumber;
	}

	public String getIfscCode() {
		return ifscCode;
	}

	public void setIfscCode(String ifscCode) {
		this.ifscCode = ifscCode;
	}

	public String getBankName() {
		return bankName;
	}

	public void setBankName(String bankName) {
		this.bankName = bankName;
	}

	public String getBranch() {
		return branch;
	}

	public void setBranch(String branch) {
		this.branch = branch;
	}

	public Float getOpeningBalance() {
		return openingBalance;
	}

	public void setOpeningBalance(Float openingBalance) {
		this.openingBalance = openingBalance;
	}

	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 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;  
	}

	
}
