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.HashMap;
import java.util.LinkedHashMap;
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.db.GetDBConnection;
import com.reallinkbilling.utils.GetAccountListForDrCr;
import com.reallinkbilling.utils.GetTypeOfPaymentList;
import com.reallinkbilling.utils.MaintainCloseingBalUtil;

public class AddAccountDebitEntry extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 7602875342480240049L;
	private HttpSession session;
	private String entryDate;
	private String accountId;
	private Float amount;
	private String typeOfPayment;
	private String entryDetails;
	
	private Map<String,String> customerSearchOptionList = new HashMap<String,String>();
	private String customerSearchOption;
	private String defaultValue;
	
	private SessionMap<String,Object> sessionMap;
	
	Map<String,String> accountList = new LinkedHashMap<String,String>();
	List<String> paymentTypeList = new ArrayList<String>();
	
	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{
	        	
	        	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
					{
						java.util.Date date = new java.util.Date();
		        	      long t = date.getTime();	        	     
		        	      java.sql.Time time = new java.sql.Time(t);
						
						String user = (String) session.getAttribute("userFullName");
						String userName = "";
						
						try
						{
							userName = user.split(" ")[0];
						}catch(Exception e)
						{
							userName = user;
						}
						
					
						connection = GetDBConnection.getDBConnection(db);
						connection.setAutoCommit(false);
						
						sql = "SELECT "
								+ "entry_id "
								+ "FROM "
								+ "bank_account_credit_debit_master "
								+ "WHERE "
								+ "shop_id = ? "
								+ "AND "
								+ "shop_code = ? "
								+ "ORDER BY "
								+ "entry_id "
								+ "DESC LIMIT 1;";
						
					
					preparedStatement = connection.prepareStatement(sql);
					preparedStatement.setString(1, shopId);
					preparedStatement.setString(2, shopCode);
					
					resultSet = preparedStatement.executeQuery();
					
					int entryId = 1;
				
					if(resultSet.next())
					{
						if(!(resultSet.getString(1) == null))
						{
							entryId = Integer.parseInt(resultSet.getString(1));
							entryId = entryId + 1;
							
						}
						
					}
					else
					{	entryId =1;
						
					}
					
	        		if(resultSet != null)
	        		{
	        			resultSet.close();
	        			resultSet = null;
	        		}
	        		if(preparedStatement!= null)
	        		{
	        			preparedStatement.close();
	        			preparedStatement = null;
	        		}
	        		String accountNumber = "";
	        		
	        		sql = "SELECT "
	        				+ "account_number "
	        				+ "FROM "
	        				+ "bank_account "
	        				+ "WHERE "
	        				+ "account_id  = ? "
	        				+ "AND "
	        				+ "shop_id = ? "
	        				+ "AND "
	        				+ "shop_code = ?";
	        			
	        		preparedStatement = connection.prepareStatement(sql);
	        		
	        		preparedStatement.setString(1, this.getAccountId());
	        		preparedStatement.setString(2, shopId);
	        		preparedStatement.setString(3, shopCode);
	        		
	        		resultSet = preparedStatement.executeQuery();
	        		if(resultSet.next())
	        		{
	        			accountNumber = resultSet.getString(1);
	        		}
	        		

	        		if(resultSet != null)
	        		{
	        			resultSet.close();
	        			resultSet = null;
	        		}
	        		if(preparedStatement!= null)
	        		{
	        			preparedStatement.close();
	        			preparedStatement = null;
	        		}
						
						sql = "INSERT "
								+ "INTO "
								+ "bank_account_credit_debit_master "
								+ "("
								+ "entry_id,"
								+ "shop_id,"
								+ "shop_code,"
								+ "account_id,"
								+ "account_number,"
								+ "entry_date,"
								+ "entry_time,"
								+ "entry_type,"
								+ "amount,"
								+ "payment_type,"
								+ "entry_by,"
								+ "entry_details,"
								+ "entry_source) "
								+ "VALUES "
								+ "(?,?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?)";
						
						preparedStatement = connection.prepareStatement(sql);
						
						preparedStatement.setInt(1, entryId);
						preparedStatement.setString(2, shopId);
						preparedStatement.setString(3, shopCode);
						preparedStatement.setString(4, this.getAccountId());
						preparedStatement.setString(5, accountNumber);
						preparedStatement.setString(6, this.getEntryDate());
						preparedStatement.setTime(7, time);
						preparedStatement.setString(8, "DEBIT");
						preparedStatement.setFloat(9, this.getAmount());
						preparedStatement.setString(10, this.getTypeOfPayment());
						preparedStatement.setString(11, userName);
						preparedStatement.setString(12, this.getEntryDetails());
						preparedStatement.setString(13, "BANK DEBIT ");
						
						int rowInsetred = preparedStatement.executeUpdate();
						
						if(rowInsetred > 0)
						{
							boolean isCloseingBalMaintained = MaintainCloseingBalUtil.maintainCloseingBal(this.getAccountId(),"DEBIT", this.getEntryDate(), this.getAmount(), userName, connection, this.getSessionMap());
							
							if(isCloseingBalMaintained)
							{
								connection.commit();
								result = SUCCESS;
								addActionMessage("Account debit entry added successfully!");
							}
							
						}
						else
						{
							connection.rollback();
							result = ERROR;
							addActionError("Sorry! Account debit not added. Please try again!");
						}
						
						
						
					}catch (SQLException e) {
						try {connection.rollback();} catch (SQLException e1) {}
						result = ERROR;
						
						addActionError(e.getErrorCode()+" || "+e.getMessage() +" ||Debit entry details not added !");
					} catch (IOException e) {
						
						result = ERROR;						
						addActionError(e.getMessage()+" || "+e.getCause()+" ||Debit entry details not added !");
					}finally {
						if(resultSet != null)
		   				{
		   					try {resultSet.close(); resultSet = null;}catch(SQLException sqe){}   					
		   				}
						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() {
		session=ServletActionContext.getRequest().getSession(false); 
		customerSearchOptionList.put("BYNAME", "BY NAME");
    	customerSearchOptionList.put("BYMOBILE", "BY MOBILE");
    	customerSearchOptionList.put("BYADDRESS","BY ADDRESS");
		this.setCustomerSearchOption("BYNAME");
		this.setDefaultValue("BYNAME");
		
		this.setAccountList(GetAccountListForDrCr.getAccountList(this.getSessionMap()));        	
    	this.setPaymentTypeList(GetTypeOfPaymentList.getTypeOfPaymentList());
		
		if(this.getAccountId().equals(""))
		{
			addActionError("Please select account number!");
		}
		
		if(!hasActionErrors())
		{
			if(this.getAmount() == null || this.getAmount().equals(""))
			{
				addActionError("Please provide correct amount!");
			}
		}
	}
	
	
	public Map<String, String> getAccountList() {
		return accountList;
	}

	public void setAccountList(Map<String, String> accountList) {
		this.accountList = accountList;
	}

	public List<String> getPaymentTypeList() {
		return paymentTypeList;
	}

	public void setPaymentTypeList(List<String> paymentTypeList) {
		this.paymentTypeList = paymentTypeList;
	}

	public HttpSession getSession() {
		return session;
	}
	public void setSession(HttpSession session) {
		this.session = session;
	}
	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 static long getSerialversionuid() {
		return serialVersionUID;
	}
	public String getEntryDate() {
		return entryDate;
	}
	public void setEntryDate(String entryDate) {
		this.entryDate = entryDate;
	}
	public String getAccountId() {
		return accountId;
	}
	public void setAccountId(String accountId) {
		this.accountId = accountId;
	}
	public Float getAmount() {
		return amount;
	}
	public void setAmount(Float amount) {
		this.amount = amount;
	}
	public String getTypeOfPayment() {
		return typeOfPayment;
	}
	public void setTypeOfPayment(String typeOfPayment) {
		this.typeOfPayment = typeOfPayment;
	}
	public String getEntryDetails() {
		return entryDetails;
	}
	public void setEntryDetails(String entryDetails) {
		this.entryDetails = entryDetails;
	}


	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;  
	}
	
}
