package com.reallinkbilling.update;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.db.GetDBConnection;

public class UpdateGodown extends ActionSupport implements SessionAware {

	private static final long serialVersionUID = 1L;

	private SessionMap<String, Object> sessionMap;

	private String godownId;
	private String godownCode;
	private String godownName;
	private String godownAddress;
	private String originalGodownCode;

	public String execute() {

		String result = "login";

		if (this.getSessionMap() == null
				|| this.getSessionMap().get("login") == null) {

			addActionMessage("Please Logout and Login again!");
			result = "login";

		} else {

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

			Connection connection = null;
			PreparedStatement preparedStatement = null;

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

			try {

				connection = GetDBConnection.getDBConnection(db);

				/*
				 * Update Godown Details
				 */
				String sql = "UPDATE shop_godown_master SET "
						+ "godown_code = ?, "
						+ "godown_name = ?, "
						+ "godown_address = ? "
						+ "WHERE godown_id = ? "
						+ "AND shop_id = ? "
						+ "AND shop_code = ?";

				preparedStatement = connection.prepareStatement(sql);

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

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

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

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

				preparedStatement.setString(
						5,
						shopId);

				preparedStatement.setString(
						6,
						shopCode);

				int k = preparedStatement.executeUpdate();

				if (k > 0) {

					result = SUCCESS;

					addActionMessage(
							"Godown details updated successfully!");

				} else {

					result = ERROR;

					addActionError(
							"Godown details not updated! Please try again!");
				}

			} catch (SQLException e) {

				result = "error";

				addActionError(
						e.getErrorCode()
								+ " || "
								+ e.getMessage()
								+ " || Something Went Wrong!");

			} catch (Exception e) {

				result = "error";

				addActionError(
						e.getMessage()
								+ " || Something Went Wrong!");

			} finally {

				if (preparedStatement != null) {

					try {
						preparedStatement.close();
					} catch (SQLException e) {
					}
				}

				if (connection != null) {

					try {
						connection.close();
					} catch (SQLException e) {
					}
				}
			}
		}

		return result;
	}

	@Override
	public void validate() {

		/*
		 * Validate Godown Code
		 */
		if (this.getGodownCode() == null
				|| this.getGodownCode().trim().equals("")) {

			addActionError("Please provide godown code!");
		}

		/*
		 * Validate Godown Code Format
		 */
		if (!hasActionErrors()) {

			Pattern p = Pattern.compile(
					"[^A-Z0-9 ]",
					Pattern.CASE_INSENSITIVE);

			Matcher m = p.matcher(
					this.getGodownCode()
							.trim()
							.toUpperCase());

			boolean res = m.find();

			if (res) {

				addActionError(
						"Godown Code Cannot contain spaces and special characters!");
			}
		}

		/*
		 * Check Duplicate Godown Code
		 *
		 * Only perform this check if the code
		 * has been changed.
		 */
		if (!hasActionErrors()) {

			String currentGodownCode =
					this.getGodownCode()
							.trim()
							.toUpperCase();

			String oldGodownCode =
					this.getOriginalGodownCode();

			if (oldGodownCode == null) {
				oldGodownCode = "";
			}

			if (!currentGodownCode.equals(
					oldGodownCode.trim().toUpperCase())) {

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

				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);

					/*
					 * Check whether another godown with
					 * the same code exists for this shop.
					 */
					String sql =
							"SELECT COUNT(*) "
							+ "FROM shop_godown_master "
							+ "WHERE godown_code = ? "
							+ "AND godown_id != ? "
							+ "AND shop_id = ? "
							+ "AND shop_code = ?";

					preparedStatement =
							connection.prepareStatement(sql);

					preparedStatement.setString(
							1,
							currentGodownCode);

					preparedStatement.setString(
							2,
							this.getGodownId());

					preparedStatement.setString(
							3,
							shopId);

					preparedStatement.setString(
							4,
							shopCode);

					resultSet =
							preparedStatement.executeQuery();

					if (resultSet.next()
							&& resultSet.getInt(1) > 0) {

						addActionError(
								"Godown with provided code is already added!");
					}

				} catch (Exception e) {

					addActionError(
							"Error checking godown code availability!");

				} finally {

					if (resultSet != null) {

						try {
							resultSet.close();
						} catch (SQLException e) {
						}
					}

					if (preparedStatement != null) {

						try {
							preparedStatement.close();
						} catch (SQLException e) {
						}
					}

					if (connection != null) {

						try {
							connection.close();
						} catch (SQLException e) {
						}
					}
				}
			}
		}

		/*
		 * Validate Godown Name
		 */
		if (!hasActionErrors()) {

			if (this.getGodownName() == null
					|| this.getGodownName().trim().equals("")) {

				addActionError(
						"Please provide godown name!");
			}
		}

		/*
		 * Validate Godown Address
		 */
		if (!hasActionErrors()) {

			if (this.getGodownAddress() == null
					|| this.getGodownAddress().trim().equals("")) {

				addActionError(
						"Please provide godown address!");
			}
		}
	}

	/*
	 * Getters and Setters
	 */

	public String getGodownId() {
		return godownId;
	}

	public void setGodownId(String godownId) {
		this.godownId = godownId;
	}

	public String getGodownCode() {
		return godownCode;
	}

	public void setGodownCode(String godownCode) {
		this.godownCode = godownCode;
	}

	public String getGodownName() {
		return godownName;
	}

	public void setGodownName(String godownName) {
		this.godownName = godownName;
	}

	public String getGodownAddress() {
		return godownAddress;
	}

	public void setGodownAddress(String godownAddress) {
		this.godownAddress = godownAddress;
	}

	public String getOriginalGodownCode() {
		return originalGodownCode;
	}

	public void setOriginalGodownCode(String originalGodownCode) {
		this.originalGodownCode = originalGodownCode;
	}

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

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

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