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.LabelMasterDAO;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.GetNewIdForNewEntry;
import com.reallinkbilling.utils.LabelCapSchema;
import com.reallinkbilling.utils.PackingMasterOptions;

public class AddNewLabel extends ActionSupport implements SessionAware {

	private static final long serialVersionUID = 1L;

	private SessionMap<String, Object> sessionMap;
	private HttpSession session;
	private String labelName;
	private String labelDetails;
	private String labelCode;
	private String customerId;
	private Map<String, String> customerList = new LinkedHashMap<String, String>();
	private List<LabelMasterDAO> labelMasterList = new ArrayList<LabelMasterDAO>();

	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.labelCodeExists(connection, shopId, shopCode, this.getLabelCode().trim().toUpperCase())) {
					result = ERROR;
					addActionError("Label code already exists!");
				} else {
					int newLabelId = GetNewIdForNewEntry.getNewIdForNewEntry("shop_label_master", "label_id", this.getSessionMap(), connection);
					if (newLabelId <= 0) {
						newLabelId = 1;
					}
					String sql = "INSERT INTO shop_label_master ("
							+ "label_id,shop_id,shop_code,label_name,label_details,label_code,customer_id,customer_name,add_date,entry_by) "
							+ "VALUES (?,?,?,?,?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?)";
					preparedStatement = connection.prepareStatement(sql);
					preparedStatement.setInt(1, newLabelId);
					preparedStatement.setString(2, shopId);
					preparedStatement.setString(3, shopCode);
					preparedStatement.setString(4, this.getLabelName().trim().toUpperCase());
					preparedStatement.setString(5, this.getLabelDetails() == null ? "" : this.getLabelDetails().trim().toUpperCase());
					preparedStatement.setString(6, this.getLabelCode().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("Label added successfully!");
						this.setLabelName("");
						this.setLabelDetails("");
						this.setLabelCode("");
						this.setCustomerId("");
					} else {
						result = ERROR;
						addActionError("Label could not be added!");
					}
				}
				this.setCustomerList(PackingMasterOptions.customerOptions(connection, shopId, shopCode));
				this.setLabelMasterList(PackingMasterOptions.labelRows(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.getLabelName() == null || this.getLabelName().trim().equals("")) {
			addActionError("Please provide label name!");
		}
		if (!hasActionErrors()) {
			if (this.getLabelName().trim().length() > 200) {
				addActionError("Label name is too long!");
			}
		}
		if (!hasActionErrors()) {
			if (this.getLabelCode() == null || this.getLabelCode().trim().equals("")) {
				addActionError("Please provide label code!");
			} else if (this.getLabelCode().trim().contains(" ")) {
				addActionError("Label code should not contain spaces!");
			} else if (this.getLabelCode().trim().length() > 50) {
				addActionError("Label code is too long!");
			}
		}
		if (!hasActionErrors()) {
			if (this.getLabelDetails() != null && this.getLabelDetails().trim().length() > 500) {
				addActionError("Label 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.setLabelMasterList(PackingMasterOptions.labelRows(connection, shopId, shopCode));
			if (!hasActionErrors() && this.getLabelCode() != null) {
				if (PackingMasterOptions.labelCodeExists(connection, shopId, shopCode, this.getLabelCode().trim().toUpperCase())) {
					addActionError("Label 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 getLabelName() {
		return labelName;
	}

	public void setLabelName(String labelName) {
		this.labelName = labelName;
	}

	public String getLabelDetails() {
		return labelDetails;
	}

	public void setLabelDetails(String labelDetails) {
		this.labelDetails = labelDetails;
	}

	public String getLabelCode() {
		return labelCode;
	}

	public void setLabelCode(String labelCode) {
		this.labelCode = labelCode;
	}

	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<LabelMasterDAO> getLabelMasterList() {
		return labelMasterList;
	}

	public void setLabelMasterList(List<LabelMasterDAO> labelMasterList) {
		this.labelMasterList = labelMasterList;
	}

	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;
	}
}
