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.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 AddAccountTransferEntry extends ActionSupport implements SessionAware {

	private static final long serialVersionUID = 5312518423170125004L;

	private HttpSession session;
	private String entryDate;
	private String fromAccountId;
	private String toAccountId;
	private Float amount;
	private String typeOfPayment;
	private String entryDetails;

	private Map<String, String> accountList = new LinkedHashMap<String, String>();
	private List<String> paymentTypeList = new ArrayList<String>();
	private SessionMap<String, Object> sessionMap;

	private static class AccountInfo {
		private final String accountNumber;
		private final String accountHolderName;

		private AccountInfo(String accountNumber, String accountHolderName) {
			this.accountNumber = accountNumber == null ? "" : accountNumber;
			this.accountHolderName = accountHolderName == null ? "" : accountHolderName;
		}
	}

	public String execute() {
		String result = "login";
		session = ServletActionContext.getRequest().getSession(false);

		if (session == null || session.getAttribute("login") == null) {
			addActionMessage(this.getText("message.error.plzloginfirst"));
			return result;
		}

		Connection connection = null;
		boolean oldAutoCommit = true;

		try {
			String shopId = (String) this.getSessionMap().get("shopId");
    		String shopCode = (String) this.getSessionMap().get("shopCode");
    		
			String db = (String) session.getAttribute("db");
			String userName = getUserName();

			java.util.Date date = new java.util.Date();
			long timeInMillis = date.getTime();
			java.sql.Time time = new java.sql.Time(timeInMillis);

			connection = GetDBConnection.getDBConnection(db);
			oldAutoCommit = connection.getAutoCommit();
			connection.setAutoCommit(false);

			int startEntryId = getNextEntryId(connection, shopId, shopCode);
			AccountInfo fromAccountInfo = getAccountInfo(connection, this.getFromAccountId(), shopId, shopCode);
			AccountInfo toAccountInfo = getAccountInfo(connection, this.getToAccountId(), shopId, shopCode);
			String transferReference = "TRF-" + startEntryId;
			String transferEntryDetails = buildTransferEntryDetails(this.getEntryDetails(), fromAccountInfo, toAccountInfo,
					transferReference);

			insertEntry(connection, startEntryId, shopId, shopCode, this.getFromAccountId(), fromAccountInfo.accountNumber,
					this.getEntryDate(), time, "DEBIT", this.getAmount(), this.getTypeOfPayment(), userName,
					transferEntryDetails, "ACCOUNT TRANSFER DR");

			insertEntry(connection, startEntryId + 1, shopId, shopCode, this.getToAccountId(), toAccountInfo.accountNumber,
					this.getEntryDate(), time, "CREDIT", this.getAmount(), this.getTypeOfPayment(), userName,
					transferEntryDetails, "ACCOUNT TRANSFER CR");

			boolean debitClosingUpdated = MaintainCloseingBalUtil.maintainCloseingBal(this.getFromAccountId(), "DEBIT",
					this.getEntryDate(), this.getAmount(), userName, connection, this.getSessionMap());
			boolean creditClosingUpdated = MaintainCloseingBalUtil.maintainCloseingBal(this.getToAccountId(), "CREDIT",
					this.getEntryDate(), this.getAmount(), userName, connection, this.getSessionMap());

			if (debitClosingUpdated && creditClosingUpdated) {
				connection.commit();
				clearForm();
				result = "success";
				addActionMessage(this.getText("message.success.accountTransferEntryAddedSuccessfully"));
			} else {
				connection.rollback();
				result = "error";
				addActionError(this.getText("message.error.sryAccountTransferNotAddedPlzTryAgain"));
			}

		} catch (SQLException e) {
			result = "error";
			if (connection != null) {
				try {
					connection.rollback();
				} catch (SQLException rollbackEx) {
					// Ignored, original exception is returned to user.
				}
			}
			addActionError(
					e.getErrorCode() + " || " + e.getMessage() + " || " + this.getText("message.error.entryDetailsNotAdded"));
		} catch (IOException e) {
			result = "error";
			if (connection != null) {
				try {
					connection.rollback();
				} catch (SQLException rollbackEx) {
					// Ignored, original exception is returned to user.
				}
			}
			addActionError(
					e.getMessage() + " || " + e.getCause() + " || " + this.getText("message.error.entryDetailsNotAdded"));
		} finally {
			if (connection != null) {
				try {
					connection.setAutoCommit(oldAutoCommit);
				} catch (SQLException e) {
				}
				try {
					connection.close();
					connection = null;
				} catch (SQLException e) {
				}
			}
		}

		return result;
	}

	private String getUserName() {
		String user = (String) session.getAttribute("userFullName");
		String userName;

		try {
			userName = user.split(" ")[0];
		} catch (Exception e) {
			userName = user;
		}
		return userName;
	}

	private int getNextEntryId(Connection connection, String shopId, String shopCode) throws SQLException {
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		int entryId = 1;

		try {
			String 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();

			if (resultSet.next() && resultSet.getString(1) != null) {
				entryId = Integer.parseInt(resultSet.getString(1)) + 1;
			}
		} finally {
			if (resultSet != null) {
				try {
					resultSet.close();
					resultSet = null;
				} catch (SQLException e) {
				}
			}
			if (preparedStatement != null) {
				try {
					preparedStatement.close();
					preparedStatement = null;
				} catch (SQLException e) {
				}
			}
		}

		return entryId;
	}

	private AccountInfo getAccountInfo(Connection connection, String accountId, String shopId, String shopCode)
			throws SQLException {
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		String accountNumber = "";
		String accountHolderName = "";

		try {
			String sql = "SELECT account_number, account_holder_name FROM bank_account "
					+ "WHERE account_id = ? AND shop_id = ? AND shop_code = ?";

			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, accountId);
			preparedStatement.setString(2, shopId);
			preparedStatement.setString(3, shopCode);

			resultSet = preparedStatement.executeQuery();
			if (resultSet.next()) {
				accountNumber = resultSet.getString(1);
				accountHolderName = resultSet.getString(2);
			}
		} finally {
			if (resultSet != null) {
				try {
					resultSet.close();
					resultSet = null;
				} catch (SQLException e) {
				}
			}
			if (preparedStatement != null) {
				try {
					preparedStatement.close();
					preparedStatement = null;
				} catch (SQLException e) {
				}
			}
		}

		return new AccountInfo(accountNumber, accountHolderName);
	}

	private String buildTransferEntryDetails(String userEntryDetails, AccountInfo fromAccountInfo, AccountInfo toAccountInfo,
			String transferReference) {
		String userDetails = userEntryDetails == null ? "" : userEntryDetails.trim();
		String autoDetails = "Transfer form account number and name: " + fromAccountInfo.accountNumber + "-"
				+ fromAccountInfo.accountHolderName + " | Transfer to account number and name: "
				+ toAccountInfo.accountNumber + "-" + toAccountInfo.accountHolderName + " | Transfer Ref: "
				+ transferReference;

		if (userDetails.equals("")) {
			return autoDetails;
		}

		return userDetails + " | " + autoDetails;
	}

	private void insertEntry(Connection connection, int entryId, String shopId, String shopCode, String accountId,
			String accountNumber, String entryDate, java.sql.Time time, String entryType, Float amount, String paymentType,
			String entryBy, String entryDetails, String entrySource) throws SQLException {
		PreparedStatement preparedStatement = null;
		try {
			String 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, accountId);
			preparedStatement.setString(5, accountNumber);
			preparedStatement.setString(6, entryDate);
			preparedStatement.setTime(7, time);
			preparedStatement.setString(8, entryType);
			preparedStatement.setFloat(9, amount);
			preparedStatement.setString(10, paymentType);
			preparedStatement.setString(11, entryBy);
			preparedStatement.setString(12, entryDetails);
			preparedStatement.setString(13, entrySource);
			preparedStatement.executeUpdate();
		} finally {
			if (preparedStatement != null) {
				try {
					preparedStatement.close();
					preparedStatement = null;
				} catch (SQLException e) {
				}
			}
		}
	}

	private void clearForm() {
		this.setFromAccountId("");
		this.setToAccountId("");
		this.setAmount(0.0f);
		this.setTypeOfPayment("");
		this.setEntryDetails("");
	}

	@Override
	public void validate() {
		session = ServletActionContext.getRequest().getSession(false);

		this.setAccountList(GetAccountListForDrCr.getAccountList(this.getSessionMap()));
		this.setPaymentTypeList(GetTypeOfPaymentList.getTypeOfPaymentList());

		if (this.getFromAccountId() == null || this.getFromAccountId().trim().equals("")) {
			addActionError(this.getText("message.error.plzSelectFromAccount"));
		}

		if (this.getToAccountId() == null || this.getToAccountId().trim().equals("")) {
			addActionError(this.getText("message.error.plzSelectToAccount"));
		}

		if (!hasActionErrors() && this.getFromAccountId().equals(this.getToAccountId())) {
			addActionError(this.getText("message.error.fromAndToAccountShouldNotBeSame"));
		}

		if (!hasActionErrors()) {
			if (this.getAmount() == null || this.getAmount() <= 0) {
				addActionError(this.getText("message.error.plzProvideCorrectAmount"));
			}
		}
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public String getEntryDate() {
		return entryDate;
	}

	public void setEntryDate(String entryDate) {
		this.entryDate = entryDate;
	}

	public String getFromAccountId() {
		return fromAccountId;
	}

	public void setFromAccountId(String fromAccountId) {
		this.fromAccountId = fromAccountId;
	}

	public String getToAccountId() {
		return toAccountId;
	}

	public void setToAccountId(String toAccountId) {
		this.toAccountId = toAccountId;
	}

	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 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 SessionMap<String, Object> getSessionMap() {
		return sessionMap;
	}

	public void setSessionMap(SessionMap<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}

	@SuppressWarnings("unchecked")
	public void setSession(Map<String, Object> map) {
		sessionMap = (SessionMap<String, Object>) map;
	}
}
