package com.reallinkbilling.add;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
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;
import com.reallinkbilling.resource.CheckAlreadyAvailable;
import com.reallinkbilling.resource.GetNewIdForNewEntry;

public class AddNewGodown extends ActionSupport implements SessionAware {

	private static final long serialVersionUID = 6208411094853732491L;

	private SessionMap<String, Object> sessionMap;

	private String godownCode;
	private String godownName;
	private String godownAddress;

	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;
			ResultSet resultSet = null;

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

			try {

				connection = GetDBConnection.getDBConnection(db);

				int newGodownId = GetNewIdForNewEntry.getNewIdForNewEntry(
						"shop_godown_master",
						"godown_id",
						this.getSessionMap(),
						connection);

				if (newGodownId != 0) {

					sql = "INSERT INTO shop_godown_master "
							+ "(shop_id, shop_code, godown_id, godown_code, godown_name, godown_address) "
							+ "VALUES (?,?,?,?,?,?)";

					preparedStatement = connection.prepareStatement(sql);

					preparedStatement.setString(1, shopId);
					preparedStatement.setString(2, shopCode);
					preparedStatement.setInt(3, newGodownId);
					preparedStatement.setString(4, this.getGodownCode().trim().toUpperCase());
					preparedStatement.setString(5, this.getGodownName().trim().toUpperCase());
					preparedStatement.setString(6, this.getGodownAddress().trim().toUpperCase());

					int k = preparedStatement.executeUpdate();

					if (k > 0) {

						result = SUCCESS;
						addActionMessage("Godown details added Successfully!");

					} else {

						result = ERROR;
						addActionError("Godown details not added! Please try again!");
					}

				} else {

					result = ERROR;
					addActionError("Godown details not added! 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 (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 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
		 */
		if (!hasActionErrors()) {

			String isGodownAdded = "false";

			String[] result = new String[2];

			String condition = "NA";

			result = new CheckAlreadyAvailable().checkAvaibility(
					"shop_godown_master",
					"godown_code",
					condition,
					this.getGodownCode(),
					this.getSessionMap());

			isGodownAdded = result[0];

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

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

		/*
		 * 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!");
			}
		}
	}

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