package com.reallinkbilling.report;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
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.CompositeSubProductReportDAO;
import com.reallinkbilling.db.GetDBConnection;

public class CompositeSubProductReport extends ActionSupport implements SessionAware {

	private static final long serialVersionUID = 1L;

	private SessionMap<String, Object> sessionMap;
	private HttpSession session;
	private String fromDate;
	private String toDate;
	private List<CompositeSubProductReportDAO> reportList = new ArrayList<CompositeSubProductReportDAO>();
	private String totalQuantity;
	private String totalQuantity2;

	public String execute() {
		String result = "login";
		this.setSession(ServletActionContext.getRequest().getSession(false));

		if (this.getSession() == null || this.getSession().getAttribute("login") == null) {
			addActionMessage("Please Login First !!!");
			return "login";
		}

		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;

		try {
			String db = (String) this.getSessionMap().get("db");
			String shopId = (String) this.getSessionMap().get("shopId");
			String shopCode = (String) this.getSessionMap().get("shopCode");

			connection = GetDBConnection.getDBConnection(db);

			String sql = "SELECT "
					+ "DATE_FORMAT(bill_date,'%d-%m-%Y'),"
					+ "bill_number,"
					+ "product_id,"
					+ "product_name,"
					+ "product_code,"
					+ "SUM(product_quantity),"
					+ "SUM(product_quantity_2) "
					+ "FROM "
					+ "shop_bill_sub_product_info_master "
					+ "WHERE "
					+ "shop_id = ? "
					+ "AND "
					+ "shop_code = ? "
					+ "AND "
					+ "bill_type = 'COMPOSITE-BILL' "
					+ "AND "
					+ "(bill_date BETWEEN STR_TO_DATE(?,'%d-%m-%Y') AND STR_TO_DATE(?,'%d-%m-%Y')) "
					+ "GROUP BY "
					+ "bill_date,bill_number,product_id,product_name,product_code "
					+ "ORDER BY "
					+ "bill_date,bill_number";

			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setString(1, shopId);
			preparedStatement.setString(2, shopCode);
			preparedStatement.setString(3, this.getFromDate());
			preparedStatement.setString(4, this.getToDate());

			resultSet = preparedStatement.executeQuery();

			DecimalFormat df = new DecimalFormat("##.##");
			float tQty = 0.0F;
			float tQty2 = 0.0F;

			while (resultSet.next()) {
				CompositeSubProductReportDAO reportDAO = new CompositeSubProductReportDAO();
				reportDAO.setBillDate(resultSet.getString(1));
				reportDAO.setBillNumber(resultSet.getString(2));
				reportDAO.setProductId(resultSet.getString(3));
				reportDAO.setProductName(resultSet.getString(4));
				reportDAO.setProductCode(resultSet.getString(5));
				reportDAO.setQuantity(df.format(resultSet.getFloat(6)));
				reportDAO.setQuantity2(df.format(resultSet.getFloat(7)));
				this.getReportList().add(reportDAO);

				tQty = tQty + resultSet.getFloat(6);
				tQty2 = tQty2 + resultSet.getFloat(7);
			}

			this.setTotalQuantity(df.format(tQty));
			this.setTotalQuantity2(df.format(tQty2));

			if (this.getReportList().isEmpty()) {
				addActionError("Data not found for selected date range.");
				result = ERROR;
			} else {
				result = SUCCESS;
			}
		} catch (SQLException e) {
			result = ERROR;
			addActionError(e.getErrorCode() + " || " + e.getMessage() + " || Report could not be generated!");
		} catch (Exception e) {
			result = ERROR;
			addActionError(e.getMessage() + " || Report could not be generated!");
		} 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) {
				}
			}
		}

		return result;
	}

	@Override
	public void validate() {
		if (this.getFromDate() == null || this.getToDate() == null || this.getFromDate().trim().equals("")
				|| this.getToDate().trim().equals("")) {
			addActionError("Please provide from and to date!");
		}
	}

	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 getFromDate() {
		return fromDate;
	}

	public void setFromDate(String fromDate) {
		this.fromDate = fromDate;
	}

	public String getToDate() {
		return toDate;
	}

	public void setToDate(String toDate) {
		this.toDate = toDate;
	}

	public List<CompositeSubProductReportDAO> getReportList() {
		return reportList;
	}

	public void setReportList(List<CompositeSubProductReportDAO> reportList) {
		this.reportList = reportList;
	}

	public String getTotalQuantity() {
		return totalQuantity;
	}

	public void setTotalQuantity(String totalQuantity) {
		this.totalQuantity = totalQuantity;
	}

	public String getTotalQuantity2() {
		return totalQuantity2;
	}

	public void setTotalQuantity2(String totalQuantity2) {
		this.totalQuantity2 = totalQuantity2;
	}
}
