package com.reallinkbilling.add;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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.DAO.CapMasterDAO;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.GetNewIdForNewEntry;
import com.reallinkbilling.utils.LabelCapSchema;
import com.reallinkbilling.utils.PackingMasterOptions;

public class AddNewCap extends ActionSupport implements SessionAware {

	private static final long serialVersionUID = 1L;

	private SessionMap<String, Object> sessionMap;
	private HttpSession session;
	private String capName;
	private String capDetails;
	private String capCode;
	private String customerId;
	private Map<String, String> customerList = new LinkedHashMap<String, String>();
	private List<CapMasterDAO> capMasterList = new ArrayList<CapMasterDAO>();

	public String execute() {
		String result = "login";
		session = ServletActionContext.getRequest().getSession(false);

		if (session == null || session.getAttribute("login") == null) {
			addActionMessage("Please Login First !!!");
			result = "login";
		} else {
			String shopId = (String) this.getSessionMap().get("shopId");
			String shopCode = (String) this.getSessionMap().get("shopCode");
			String db = (String) this.getSessionMap().get("db");

			Connection connection = null;
			PreparedStatement preparedStatement = null;
			try {
				LabelCapSchema.ensure(this.getSessionMap());
				connection = GetDBConnection.getDBConnection(db);

				String customerName = PackingMasterOptions.customerName(connection, shopId, shopCode, this.getCustomerId());
				if (customerName == null || customerName.trim().equals("")) {
					result = ERROR;
					addActionError("Please select a valid customer!");
				} else if (PackingMasterOptions.capCodeExists(connection, shopId, shopCode, this.getCapCode().trim().toUpperCase())) {
					result = ERROR;
					addActionError("Cap code already exists!");
				} else {
					int newCapId = GetNewIdForNewEntry.getNewIdForNewEntry("shop_cap_master", "cap_id", this.getSessionMap(), connection);
					if (newCapId <= 0) {
						newCapId = 1;
					}
					String sql = "INSERT INTO shop_cap_master ("
							+ "cap_id,shop_id,shop_code,cap_name,cap_details,cap_code,customer_id,customer_name,add_date,entry_by) "
							+ "VALUES (?,?,?,?,?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?)";
					preparedStatement = connection.prepareStatement(sql);
					preparedStatement.setInt(1, newCapId);
					preparedStatement.setString(2, shopId);
					preparedStatement.setString(3, shopCode);
					preparedStatement.setString(4, this.getCapName().trim().toUpperCase());
					preparedStatement.setString(5, this.getCapDetails() == null ? "" : this.getCapDetails().trim().toUpperCase());
					preparedStatement.setString(6, this.getCapCode().trim().toUpperCase());
					preparedStatement.setString(7, this.getCustomerId());
					preparedStatement.setString(8, customerName.trim().toUpperCase());
					preparedStatement.setString(9, new SimpleDateFormat("dd-MM-yyyy").format(new Date()));
					preparedStatement.setString(10, entryBy());
					int rows = preparedStatement.executeUpdate();
					if (rows > 0) {
						result = SUCCESS;
						addActionMessage("Cap added successfully!");
						this.setCapName("");
						this.setCapDetails("");
						this.setCapCode("");
						this.setCustomerId("");
					} else {
						result = ERROR;
						addActionError("Cap could not be added!");
					}
				}
				this.setCustomerList(PackingMasterOptions.customerOptions(connection, shopId, shopCode));
				this.setCapMasterList(PackingMasterOptions.capRows(connection, shopId, shopCode));
			} catch (SQLException e) {
				result = ERROR;
				addActionError(e.getErrorCode() + " || " + e.getMessage() + " || Something Went Wrong!");
			} catch (IOException e) {
				result = ERROR;
				addActionError(e.getMessage() + " || " + e.getCause() + " || 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() {
		if (this.getCapName() == null || this.getCapName().trim().equals("")) {
			addActionError("Please provide cap name!");
		}
		if (!hasActionErrors()) {
			if (this.getCapName().trim().length() > 200) {
				addActionError("Cap name is too long!");
			}
		}
		if (!hasActionErrors()) {
			if (this.getCapCode() == null || this.getCapCode().trim().equals("")) {
				addActionError("Please provide cap code!");
			} else if (this.getCapCode().trim().contains(" ")) {
				addActionError("Cap code should not contain spaces!");
			} else if (this.getCapCode().trim().length() > 50) {
				addActionError("Cap code is too long!");
			}
		}
		if (!hasActionErrors()) {
			if (this.getCapDetails() != null && this.getCapDetails().trim().length() > 500) {
				addActionError("Cap details are too long!");
			}
		}
		if (!hasActionErrors()) {
			if (this.getCustomerId() == null || this.getCustomerId().trim().equals("")) {
				addActionError("Please select customer!");
			}
		}

		Connection connection = null;
		try {
			LabelCapSchema.ensure(this.getSessionMap());
			connection = GetDBConnection.getDBConnection((String) this.getSessionMap().get("db"));
			String shopId = (String) this.getSessionMap().get("shopId");
			String shopCode = (String) this.getSessionMap().get("shopCode");
			this.setCustomerList(PackingMasterOptions.customerOptions(connection, shopId, shopCode));
			this.setCapMasterList(PackingMasterOptions.capRows(connection, shopId, shopCode));
			if (!hasActionErrors() && this.getCapCode() != null) {
				if (PackingMasterOptions.capCodeExists(connection, shopId, shopCode, this.getCapCode().trim().toUpperCase())) {
					addActionError("Cap code already exists!");
				}
			}
		} catch (SQLException e) {
			addActionError(e.getErrorCode() + " || " + e.getMessage() + " || Something Went Wrong!");
		} catch (IOException e) {
			addActionError(e.getMessage() + " || " + e.getCause() + " || Something Went Wrong!");
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
				}
			}
		}
	}

	private String entryBy() {
		String fullUserName = (String) this.getSessionMap().get("userFullName");
		if (fullUserName == null) {
			return "";
		}
		try {
			return fullUserName.split(" ")[0];
		} catch (Exception e) {
			return fullUserName;
		}
	}

	public String getCapName() {
		return capName;
	}

	public void setCapName(String capName) {
		this.capName = capName;
	}

	public String getCapDetails() {
		return capDetails;
	}

	public void setCapDetails(String capDetails) {
		this.capDetails = capDetails;
	}

	public String getCapCode() {
		return capCode;
	}

	public void setCapCode(String capCode) {
		this.capCode = capCode;
	}

	public String getCustomerId() {
		return customerId;
	}

	public void setCustomerId(String customerId) {
		this.customerId = customerId;
	}

	public Map<String, String> getCustomerList() {
		return customerList;
	}

	public void setCustomerList(Map<String, String> customerList) {
		this.customerList = customerList;
	}

	public List<CapMasterDAO> getCapMasterList() {
		return capMasterList;
	}

	public void setCapMasterList(List<CapMasterDAO> capMasterList) {
		this.capMasterList = capMasterList;
	}

	public SessionMap<String, Object> getSessionMap() {
		return sessionMap;
	}

	public void setSessionMap(SessionMap<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}

	public void setSession(Map<String, Object> map) {
		sessionMap = (SessionMap<String, Object>) map;
	}
}
