package com.reallinkbilling.report;



import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
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.stockTransferDetailsDAO;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.GetListResource;
import com.reallinkbilling.utils.GetProductDetailsById;

public class GetWarhouseStockTransferReport extends ActionSupport implements SessionAware {

	private static final long serialVersionUID = -8837329560734275164L;

	private SessionMap<String, Object> sessionMap;
	private HttpSession session;

	private List<stockTransferDetailsDAO> productStockTransferList =
			new ArrayList<stockTransferDetailsDAO>();

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

	private Map<String, String> warehouseList = new HashMap<String, String>();
	private String defaultwarehouse;
	
	private Map<String, String> stockTypeList = new HashMap<String, String>();
	private String defaultstockType;

	public String execute() {

		String result = "login";

		session = ServletActionContext.getRequest().getSession(false);

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

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

		} else {

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

			fileTypeList.put("pdf", "pdf");
			fileTypeList.put("xls", "xls");
			
			stockTypeList.put("ALL", "ALL");
			stockTypeList.put("AVAILABLE STOCK", "AVAILABLE STOCK");

			if (defaultstockType == null || defaultstockType.trim().isEmpty()) {
			    defaultstockType = "ALL";
			}

			warehouseList.putAll(GetListResource.getGodownList(sessionMap));
			warehouseList.put("All", "All");

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

			String sql = "";

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

			Map<String, stockTransferDetailsDAO> productMap =
					new HashMap<String, stockTransferDetailsDAO>();

			try {

				connection = GetDBConnection.getDBConnection(db);

				/*
				 * ALL WAREHOUSES
				 */
				if (this.getDefaultwarehouse().equals("All")) {

					sql = "SELECT "
					        + "product_id, "
					        + "product_name, "
					        + "SUM(in_stock_quantity) AS in_stock_quantity "
					        + "FROM warehouse_stock_master "
					        + "WHERE shop_id = ? "
					        + "AND shop_code = ? "
					        + "GROUP BY product_id, product_name ";

					if ("AVAILABLE STOCK".equals(defaultstockType)) {
					    sql += "HAVING SUM(in_stock_quantity) > 0 ";
					}

					sql += "ORDER BY product_name";

					preparedStatement = connection.prepareStatement(sql);

					preparedStatement.setString(1, shopId);
					preparedStatement.setString(2, shopCode);

					resultSet = preparedStatement.executeQuery();

					while (resultSet.next()) {

						String productId = resultSet.getString("product_id");
						String productName = resultSet.getString("product_name");

						double quantity =
								resultSet.getDouble("in_stock_quantity");

						HashMap<String, String> productDetails =
								GetProductDetailsById.getProductDetails(
										productId,
										this.getSessionMap());

						stockTransferDetailsDAO dao =
								productMap.getOrDefault(
										productId,
										new stockTransferDetailsDAO());

						dao.setProductName(productName);

						if (productDetails != null) {
							dao.setPurchaseUnit(
									productDetails.get("PURCHASEUNIT"));
						}

						dao.setInStockquantity(
								dao.getInStockquantity() + quantity);

						productMap.put(productId, dao);
					}

				}

				/*
				 * SPECIFIC WAREHOUSE / GODOWN
				 */
				else {

					String warehouseId =
							this.getDefaultwarehouse().split("-")[0];

					sql = "SELECT "
					        + "product_id, "
					        + "product_name, "
					        + "in_stock_quantity "
					        + "FROM warehouse_stock_master "
					        + "WHERE shop_id = ? "
					        + "AND shop_code = ? "
					        + "AND warehouse_id = ? ";

					if ("AVAILABLE STOCK".equals(defaultstockType)) {
					    sql += "AND in_stock_quantity > 0 ";
					}

					sql += "ORDER BY product_name";

					preparedStatement = connection.prepareStatement(sql);

					preparedStatement.setString(1, shopId);
					preparedStatement.setString(2, shopCode);
					preparedStatement.setString(3, warehouseId);

					resultSet = preparedStatement.executeQuery();

					while (resultSet.next()) {

						String productId =
								resultSet.getString("product_id");

						String productName =
								resultSet.getString("product_name");

						double quantity =
								resultSet.getDouble("in_stock_quantity");

						HashMap<String, String> productDetails =
								GetProductDetailsById.getProductDetails(
										productId,
										this.getSessionMap());

						stockTransferDetailsDAO dao =
								productMap.getOrDefault(
										productId,
										new stockTransferDetailsDAO());

						dao.setProductName(productName);

						if (productDetails != null) {
							dao.setPurchaseUnit(
									productDetails.get("PURCHASEUNIT"));
						}

						dao.setInStockquantity(
								dao.getInStockquantity() + quantity);

						productMap.put(productId, dao);
					}
				}

				/*
				 * Convert Map to List
				 */
				for (stockTransferDetailsDAO dao : productMap.values()) {

					productStockTransferList.add(dao);
				}

				if (!productStockTransferList.isEmpty()) {

					result = SUCCESS;

				} else {

					addActionError("No Stock Details Found!");
					result = SUCCESS;
				}

			} catch (SQLException e) {

				result = ERROR;

				addActionError(
						e.getErrorCode()
						+ " || "
						+ e.getMessage()
						+ " || Cannot load page !");

			} catch (Exception e) {

				result = ERROR;

				addActionError(
						e.getMessage()
						+ " || "
						+ e.getCause()
						+ " || Cannot load page !!!");

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

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

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

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

	public HttpSession getSession() {
		return session;
	}

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

	public String getDefaultfileType() {
		return defaultfileType;
	}

	public void setDefaultfileType(String defaultfileType) {
		this.defaultfileType = defaultfileType;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public List<stockTransferDetailsDAO> getProductStockTransferList() {
		return productStockTransferList;
	}

	public void setProductStockTransferList(
			List<stockTransferDetailsDAO> productStockTransferList) {

		this.productStockTransferList = productStockTransferList;
	}

	public Map<String, String> getFileTypeList() {
		return fileTypeList;
	}

	public void setFileTypeList(Map<String, String> fileTypeList) {
		this.fileTypeList = fileTypeList;
	}

	public Map<String, String> getWarehouseList() {
		return warehouseList;
	}

	public void setWarehouseList(Map<String, String> warehouseList) {
		this.warehouseList = warehouseList;
	}

	public String getDefaultwarehouse() {
		return defaultwarehouse;
	}

	public void setDefaultwarehouse(String defaultwarehouse) {
		this.defaultwarehouse = defaultwarehouse;
	}

	public Map<String, String> getStockTypeList() {
		return stockTypeList;
	}

	public void setStockTypeList(Map<String, String> stockTypeList) {
		this.stockTypeList = stockTypeList;
	}

	public String getDefaultstockType() {
		return defaultstockType;
	}

	public void setDefaultstockType(String defaultstockType) {
		this.defaultstockType = defaultstockType;
	}
	
	
}