package com.reallinkbilling.update;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
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.cipher.EncryptionDecryption;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.CheckAlreadyAvailable;
import com.reallinkbilling.utils.MaintainCloseingBalUtil;

public class UpdateBankAccountDetails extends ActionSupport implements SessionAware {

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

	private HttpSession session;

	private String key;
	private String accountId;
	private String accountHolderName;
	private String accountNumber;
	private String ifscCode;
	private String bankName;
	private String branch;
	private Float openingBalance;
	private Float oldBalance;

	private Map<String, String> customerSearchOptionList =
			new HashMap<String, String>();

	private String customerSearchOption;
	private String defaultValue;
	private String addSideBarJs;

	private SessionMap<String, Object> sessionMap;

	public String execute() throws IOException {

		String result = "login";

		session = ServletActionContext.getRequest().getSession(false);
		
//		System.out.println("========== UPDATE BANK ACCOUNT ==========");
//		System.out.println("Session Object = " + session);
//
//		if (session != null) {
//		    System.out.println("login = " + session.getAttribute("login"));
//		    System.out.println("db = " + session.getAttribute("db"));
//		    System.out.println("userFullName = " + session.getAttribute("userFullName"));
//		}
//
//		System.out.println("=========================================");
//		

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

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

			result = "login";

		} else {

			Date d = new Date();

			SimpleDateFormat dateFormat =
					new SimpleDateFormat("dd-MM-yyyy");

			String date = dateFormat.format(d);

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

			String shortName = "";

			try {

				shortName = user.split(" ")[0];

			} catch (Exception e) {

				shortName = user;
			}

			/*
			 * EasySBill session values
			 */
			String shopId =
					(String) this.getSessionMap().get("shopId");

			String shopCode =
					(String) this.getSessionMap().get("shopCode");

			Connection connection = null;
			PreparedStatement preparedStatement = null;

			String sql = "";

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

			try {

				connection =
						GetDBConnection.getDBConnection(db);

				int rowUpdated = 0;

				/*
				 * Decrypt account ID received from JSP
				 */
				String accountId =
						EncryptionDecryption.decrypt(this.getKey());

				/*
				 * Update bank account details
				 */
				sql = "UPDATE "
						+ "bank_account "
						+ "SET "
						+ "account_holder_name = ?,"
						+ "account_number = ?,"
						+ "ifsc_code = ?,"
						+ "bank_name = ?,"
						+ "branch = ?,"
						+ "opening_balance = ? "
						+ "WHERE "
						+ "account_id = ? "
						+ "AND "
						+ "shop_id = ? "
						+ "AND "
						+ "shop_code = ? ";

				preparedStatement =
						connection.prepareStatement(sql);

				preparedStatement.setString(
						1,
						this.getAccountHolderName()
								.trim()
								.toUpperCase()
				);

				preparedStatement.setString(
						2,
						this.getAccountNumber()
								.trim()
								.toUpperCase()
				);

				preparedStatement.setString(
						3,
						this.getIfscCode()
								.trim()
								.toUpperCase()
				);

				preparedStatement.setString(
						4,
						this.getBankName()
				);

				preparedStatement.setString(
						5,
						this.getBranch()
				);

				preparedStatement.setFloat(
						6,
						this.getOpeningBalance()
				);

				preparedStatement.setString(
						7,
						accountId
				);

				preparedStatement.setString(
						8,
						shopId
				);

				preparedStatement.setString(
						9,
						shopCode
				);

				rowUpdated =
						preparedStatement.executeUpdate();

				if (rowUpdated > 0) {

					boolean isCloseingBalMaintained = false;

					String accountIdString =
							String.valueOf(accountId);

					/*
					 * Remove old opening balance
					 */
					isCloseingBalMaintained =
							MaintainCloseingBalUtil.maintainCloseingBal(
									accountIdString,
									"DEBIT",
									date,
									this.getOldBalance(),
									shortName,
									connection,
									this.getSessionMap()
							);

					/*
					 * Add new opening balance
					 */
					if (isCloseingBalMaintained) {

						if (!this.getOpeningBalance().equals(0)) {

							isCloseingBalMaintained =
									MaintainCloseingBalUtil.maintainCloseingBal(
											accountIdString,
											"CREDIT",
											date,
											this.getOpeningBalance(),
											shortName,
											connection,
											this.getSessionMap()
									);
						}
					}

					result = SUCCESS;

					addActionMessage(
							this.getText(
									"message.success.bankAccountDetailsUpdatedSuccessfully"
							)
					);

				} else {

					result = ERROR;

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

			} catch (SQLException e) {

				result = "error";

				e.printStackTrace();

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

			} catch (Exception e) {

				e.printStackTrace();

				result = "error";

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

			} finally {

				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("plz Provide Account Holder Name");
		}

		if (!hasActionErrors()) {

			if (this.getAccountNumber() == null
					|| this.getAccountNumber().equals("")) {

				addActionError("plz Provide Account Number");

			} else if (this.getAccountNumber().length() > 15) {

				addActionError("plz Provide Correct Account Number");
			}
		}

		if (!hasActionErrors()) {

			if (this.getIfscCode() == null
					|| this.getIfscCode().equals("")) {

				addActionError("plz Provide Ifsc Code");
			}
		}

		if (!hasActionErrors()) {

			if (this.getBankName() == null
					|| this.getBankName().equals("")) {

				addActionError("plz Provide Bank Name");
			}
		}

		if (!hasActionErrors()) {

			if (this.getBranch() == null
					|| this.getBranch().equals("")) {

				addActionError("plz Provide Branch Name");
			}
		}

		if (!hasActionErrors()) {

			if (this.getOpeningBalance() == null
					|| this.getOpeningBalance().equals("")) {

				addActionError(
						"plz Provide Correct Opening Balance Amount"
				);
			}
		}

		/*
		 * Decrypt current account ID
		 */
		String accountId =
				EncryptionDecryption.decrypt(this.getKey());

		/*
		 * Check whether same account number already
		 * exists for another bank account.
		 */
		String condition =
				"And account_id != '" + accountId + "'";

		if (!hasActionErrors()) {

			String isAliasAdded = "false";

			String[] result = new String[2];

			result = 
			        new CheckAlreadyAvailable().checkAvaibility(
			                "bank_account",
			                "account_number",
			                condition,
			                this.getAccountNumber(),
			                this.getSessionMap()
			        );

			isAliasAdded = result[0];

			if (isAliasAdded.equals("true")) {

				addActionError("Account Is Already Added With Same Number " );
			}
		}

		/*
		 * Customer search options
		 */
		customerSearchOptionList.put(
				"BYNAME",
				"BY NAME"
		);

		customerSearchOptionList.put(
				"BYMOBILE",
				"BY MOBILE"
		);

		customerSearchOptionList.put(
				"BYADDRESS",
				"BY ADDRESS"
		);

		setCustomerSearchOption("BYNAME");
		setDefaultValue("BYNAME");
	}

	public HttpSession getSession() {
		return session;
	}

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

	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 String getKey() {
		return key;
	}

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

	public String getAddSideBarJs() {
		return addSideBarJs;
	}

	public void setAddSideBarJs(String addSideBarJs) {
		this.addSideBarJs = addSideBarJs;
	}

	@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 String getAccountId() {
		return accountId;
	}

	public void setAccountId(String accountId) {
		this.accountId = accountId;
	}

	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 Float getOldBalance() {
		return oldBalance;
	}

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