
package com.reallinkbilling.update;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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.cipher.EncryptionDecryption;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.utils.MaintainCloseingBalUtil;

public class UpdateBankAccountOpeningBalance extends ActionSupport implements SessionAware {

	/**
	 *
	 */
	private static final long serialVersionUID = 4319370706821205910L;

	private String key;

	private String openingBalanceDate;

	private Float amount;

	private String accountHolderName;

	private String accountNumber;

	private String bankName;

	private SessionMap<String, Object> sessionMap;

	private Float oldBalance;

	private HttpSession session;

	public String execute() {

		String result = "login";

		session = ServletActionContext.getRequest().getSession(false);

		if (session == null || session.getAttribute("login") == null) {

			addActionMessage(
					this.getText("message.error.plzloginfirst")
			);

			result = "login";

		} else {

			String shopId = (String) session.getAttribute("shopId");
			String shopCode = (String) session.getAttribute("shopCode");

			Connection connection = null;
			PreparedStatement preparedStatement = null;
			ResultSet resultSet = null;

			String accountId = EncryptionDecryption.decrypt(
					this.getKey()
			);

			String db = (String) session.getAttribute("db");

			String fullUserName = (String) session.getAttribute(
					"userFullName"
			);

			String splitUserName[] = new String[5];

			String updatedBy = "";

			try {

				splitUserName = fullUserName.split(" ");

				updatedBy = splitUserName[0];

			} catch (Exception e) {

				updatedBy = fullUserName;
			}

			boolean isSuccess = false;

			try {

				connection = GetDBConnection.getDBConnection(db);

				/*
				 * Update opening balance in EasySBill bank_account table.
				 *
				 * bank_account table contains:
				 *
				 * shop_id
				 * shop_code
				 * account_id
				 * account_holder_name
				 * account_number
				 * ifsc_code
				 * bank_name
				 * branch
				 * opening_balance
				 *
				 * There is NO updated_date or updated_by column.
				 */
				String updateSQL =
						"UPDATE "
						+ "bank_account "
						+ "SET "
						+ "opening_balance = ? "
						+ "WHERE "
						+ "account_id = ? "
						+ "AND "
						+ "shop_id = ? "
						+ "AND "
						+ "shop_code = ?";

				preparedStatement = connection.prepareStatement(
						updateSQL
				);

				preparedStatement.setFloat(
						1,
						this.getAmount()
				);

				preparedStatement.setString(
						2,
						accountId
				);

				preparedStatement.setString(
						3,
						shopId
				);

				preparedStatement.setString(
						4,
						shopCode
				);

				int rowCount = preparedStatement.executeUpdate();

				if (rowCount > 0) {

					/*
					 * Maintain old opening balance as DEBIT.
					 */
					boolean isClosingBalMaintained = false;

					String accountIdString = String.valueOf(
							accountId
					);

					isClosingBalMaintained =
							MaintainCloseingBalUtil.maintainCloseingBal(
									accountIdString,
									"DEBIT",
									this.getOpeningBalanceDate(),
									this.getOldBalance(),
									updatedBy,
									connection,
									this.getSessionMap()
							);

					/*
					 * Maintain new opening balance as CREDIT.
					 */
					if (isClosingBalMaintained) {

						if (this.getAmount() != null
								&& !this.getAmount().equals(0.0f)) {

							isClosingBalMaintained =
									MaintainCloseingBalUtil.maintainCloseingBal(
											accountIdString,
											"CREDIT",
											this.getOpeningBalanceDate(),
											this.getAmount(),
											updatedBy,
											connection,
											this.getSessionMap()
									);
						}
					}

					isSuccess = true;
				}

				if (isSuccess) {

					result = "success";

					addActionMessage("Bank Account Details Updated Successfully");

				} else {

					result = "error";

					addActionError("Bank Account Details Not Updated Plz Try Again");
				}

			} catch (SQLException e) {

				result = "error";

				addActionError(
						e.getErrorCode()
						+ " || "
						+ e.getMessage()
						+ " || "
						+ this.getText(
								"message.error.detailsNotUpdated"
						)
				);

			} catch (IOException e) {

				result = "error";

				addActionError(
						e.getMessage()
						+ " || "
						+ e.getCause()
						+ " || "
						+ this.getText(
								"message.error.detailsNotUpdated"
						)
				);

			} finally {

				if (resultSet != null) {

					try {

						resultSet.close();
						resultSet = null;

					} catch (SQLException 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() {

		/*
		 * Validate opening balance date
		 */
		if (this.getOpeningBalanceDate() == null
				|| this.getOpeningBalanceDate().trim().equals("")) {

			addActionError(
					this.getText(
							"message.error.plzProvideOpeningBalancedate"
					)
			);
		}

		/*
		 * Validate amount
		 */
		if (!hasActionErrors()) {

			if (this.getAmount() == null) {

				addActionError(
						this.getText(
								"message.error.plzProvideCorrectAmount"
						)
				);
			}
		}
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	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 getBankName() {
		return bankName;
	}

	public void setBankName(String bankName) {
		this.bankName = bankName;
	}

	public String getOpeningBalanceDate() {
		return openingBalanceDate;
	}

	public void setOpeningBalanceDate(String openingBalanceDate) {
		this.openingBalanceDate = openingBalanceDate;
	}

	public HttpSession getSession() {
		return session;
	}

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

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public Float getAmount() {
		return amount;
	}

	public void setAmount(Float amount) {
		this.amount = amount;
	}

	@Override
	public void setSession(Map<String, Object> arg0) {

		sessionMap = (SessionMap<String, Object>) arg0;
	}

	public SessionMap<String, Object> getSessionMap() {
		return sessionMap;
	}

	public void setSessionMap(
			SessionMap<String, Object> sessionMap) {

		this.sessionMap = sessionMap;
	}

	public Float getOldBalance() {
		return oldBalance;
	}

	public void setOldBalance(Float oldBalance) {
		this.oldBalance = oldBalance;
	}
}
