package com.reallinkbilling.delete;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
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.PurchaseInvoiceInformationDAO;
import com.reallinkbilling.DAO.PurchaseProductInfoDAO;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.GetListResource;
import com.reallinkbilling.utils.GetAccountListForDrCr;

public class DeleteEditProductFromPurchaseList extends ActionSupport implements SessionAware,Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = -1518042868893424844L;
	
	
	private HttpSession session;
	private SessionMap<String,Object> sessionMap;
	

	private String purchaseDateTime;
	private String productName;
	private Float amount;
	private Float discount;
	private Float quantity;
	private String purchaseUnit;
	private Float purchaseRate;
	private String taxId;
	private Float frightCharges;
	private Float otherExpense;
	private String purchaseId;
	private String supplierName;
	private String invoiceNumber;
	private String comments;
	private File invoiceImage;
	private String invoiceImageContentType;
	private boolean addToStock;
	private Map<String,String> taxList = new LinkedHashMap<String,String>();
	private Map<String,String> unitList = new LinkedHashMap<String,String>();
	
	private PurchaseInvoiceInformationDAO purchaseInvoiceInformationDAO = null;
	
	private List<PurchaseProductInfoDAO> purchaseProductInfoList = null;
	private List<PurchaseProductInfoDAO> deletedProductInfoList = null;
	private Map<String,String> paymentTypeList = new  LinkedHashMap<String,String>();
	private String paymentDefaultValue;
	private String purchaseBy;
	private String viewPurchaseInvoice;
	
	private Float totalPurchaseAmount;
	
	private Float totalNettAmount;
	private Float totalCGST;
	private Float totalSGST;
	private Float totalIGST;
	
	private DecimalFormat df;
	private String amountPaid;
	private String productNameForDelete;
	
	private Map<String,String> rateTypeList = new  LinkedHashMap<String,String>();
	private String rateTyprDefaultValue;
	private String serialBatchNo;
	
	private Map<String,String> accountList = new LinkedHashMap<String,String>();
	private List<String> paymentTypeList2 = new ArrayList<String>();
	
	@SuppressWarnings("unchecked")
	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
	        {
	        	
	        	paymentTypeList.put("CASH","CASH");
	        	paymentTypeList.put("CREDIT","CREDIT");
	        	
	        	
	        	paymentTypeList2.add("CASH");
	        	paymentTypeList2.add("UPI");
	        	paymentTypeList2.add("RTGS");
	        	paymentTypeList2.add("NEFT");
	        	
	        	
	        	
	        	 this.setAccountList(GetAccountListForDrCr.getAccountList(this.getSessionMap())); 
	     		
	        	 
	        	 
	        	this.getRateTypeList().put("INCLUDINGGST", "Including GST");
	        	this.getRateTypeList().put("EXCLUDINGGST", "Excluding GST");
	        	
	        	
	        Connection connection = null;
			PreparedStatement preparedStatement = null;

			String sql = "";			
			String db = (String)  this.getSessionMap().get("db");
			
	        	 df = new DecimalFormat("#.##");
	        	purchaseInvoiceInformationDAO = (PurchaseInvoiceInformationDAO) this.getSessionMap().get("purchaseInformation");
	        	purchaseProductInfoList = (List<PurchaseProductInfoDAO>)  this.getSessionMap().get("purchaseProductList");
	        	
	        	this.setDeletedProductInfoList((List<PurchaseProductInfoDAO>)  this.getSessionMap().get("deletedProductInfoList"));
	        	
	        	this.setRateTyprDefaultValue(purchaseInvoiceInformationDAO.getRateType());
	        	if(deletedProductInfoList == null)
	        	{
	        		deletedProductInfoList = new ArrayList<PurchaseProductInfoDAO>();
	        	}
	        	
	        	if(purchaseInvoiceInformationDAO != null && purchaseProductInfoList != null)
	        	{
	        		
	        		
	        	if(getProductNameForDelete() != null || getProductNameForDelete().equals(""))
	        	{
	        		int removeIndexCount = 0;
		        	int i = 0;
		        	boolean isPurchaseProductRemovedFromDB = false;
		        	
		        	for(PurchaseProductInfoDAO productInfoDAO : purchaseProductInfoList)
		        	{
		        		String listProductName = productInfoDAO.getProductName();
		        		
		        		
		        		if(this.getProductNameForDelete().equals(listProductName))
		        		{
		        			if(purchaseInvoiceInformationDAO.isPurchaseSaved())		        				
		        			{
		        				
		        			try
		        			{
		        			
								connection = GetDBConnection.getDBConnection(db);
		        				connection.setAutoCommit(false);
		        				sql = "delete from productpurchaseinfo "
		        						+ "where productname = '"+listProductName.trim()+"' "
		        						+ "and "
		        						+ "invoicenumber = '"+purchaseInvoiceInformationDAO.getInvoiceNumber()+"' "
		        						+ "and "
		        						+ "purchaseid = '"+purchaseInvoiceInformationDAO.getPurchaseId()+"'";
		        				
		        		
		        				preparedStatement = connection.prepareStatement(sql);
		        				
		        				int rowDeleted = 1;
		        				
		        				//preparedStatement.executeUpdate();
		        				
		        				
		        				if(rowDeleted>0)
		        				{
		        					//connection.commit();		        					
		        					isPurchaseProductRemovedFromDB = true;		        					
		        					removeIndexCount = i;
		        				}
		        				else
		        				{
		        					result = "error";		        					
		        					addActionError("1.Product not removed from list !");
		        				}
		        					
		        				
		        			}
		        			catch (SQLException e) {
		        				result = "error";
		        				addActionError("2.Product not removed from list !");} 
		        			catch (IOException e) {
		        				result = "error";
		        				addActionError("3.Product not removed from list !");}
		        			finally
		        			{
		        				if(preparedStatement != null)
		        				{
		        					try {
		        						preparedStatement.close();
		        						preparedStatement = null;
		        					} catch (SQLException e) {
		        						
		        					}
		        				}
		        			}
		        			
		        			}
		        			else
		        			{
		        				isPurchaseProductRemovedFromDB = true;
		        				removeIndexCount = i;
		        			}
		        		}
		        		
		        		i++;
		        	}
		        	
		        	if(isPurchaseProductRemovedFromDB)
		        	{
		        		PurchaseProductInfoDAO dao = this.getPurchaseProductInfoList().get(removeIndexCount);
		        		this.getDeletedProductInfoList().add(dao);
		        		
		        		this.setProductName(dao.getProductId()+"-"+dao.getProductName());
		        		this.setPurchaseRate(dao.getPurchaseRate());
		        		this.setPurchaseUnit(dao.getPurchaseUnit());
		        		this.setQuantity(dao.getQuantity());
		        		this.setAmount(dao.getAmount());
		        		this.setTaxId(dao.getTaxId());
		        		this.setDiscount(dao.getDiscount());
		        		this.getPurchaseProductInfoList().remove(removeIndexCount);
		        		this.setSerialBatchNo(dao.getSerialBatchNo());
			        	 
			        	 float floatTotalPurchaseAmount = 0.0F;
			        	 float floatTotalCGST = 0.0F;
			        	 float floatTotalSGST = 0.0F;
			        	 float floatTotalIGST = 0.0F;
			        	 float floatTotalNettAmount = 0.0F;
			        	 
			        	 for (PurchaseProductInfoDAO pProductInfoDAO : this.getPurchaseProductInfoList())
			        	 {
			        		 floatTotalPurchaseAmount = floatTotalPurchaseAmount + pProductInfoDAO.getAmount();
			        		 floatTotalCGST = floatTotalCGST + pProductInfoDAO.getCgst();
			        		 floatTotalSGST = floatTotalSGST + pProductInfoDAO.getSgst();
			        		 floatTotalIGST = floatTotalIGST + pProductInfoDAO.getIgst();
			        		 floatTotalNettAmount = floatTotalNettAmount + pProductInfoDAO.getNettAmount();
			        	 }
			        	 
			        	 this.setTotalPurchaseAmount(floatTotalPurchaseAmount);
			        	 this.setTotalNettAmount(floatTotalNettAmount);
			        	 this.setTotalCGST(floatTotalCGST);
			        	 this.setTotalSGST(floatTotalSGST);
			        	 this.setTotalIGST(floatTotalIGST);
		        		
			        	 this.getPurchaseInvoiceInformationDAO().setPurchaseTotalAmount(floatTotalPurchaseAmount);
			        	 this.getPurchaseInvoiceInformationDAO().setTotalNettAmount(floatTotalNettAmount);
			        	 this.getPurchaseInvoiceInformationDAO().setTotalCGST(floatTotalCGST);
			        	 this.getPurchaseInvoiceInformationDAO().setTotalSGST(floatTotalSGST);
			        	 this.getPurchaseInvoiceInformationDAO().setTotalIGST(floatTotalIGST);
			        	 
			        	 this.setPurchaseId(this.getPurchaseInvoiceInformationDAO().getPurchaseId());
			        	 this.setSupplierName(this.getPurchaseInvoiceInformationDAO().getSupplierId()+"-"+this.getPurchaseInvoiceInformationDAO().getSupplierName());
			        	 this.setInvoiceNumber(this.getPurchaseInvoiceInformationDAO().getInvoiceNumber());
			        	 this.setPaymentDefaultValue(this.getPurchaseInvoiceInformationDAO().getPaymentType());
			        	 this.setPurchaseBy(this.getPurchaseInvoiceInformationDAO().getPurchaseBy());
			        	 this.setAddToStock(this.getPurchaseInvoiceInformationDAO().isAddToStock());
			        	 this.setPurchaseDateTime(this.getPurchaseInvoiceInformationDAO().getPurchaseDate());
			        	 
			        	/* if(purchaseInvoiceInformationDAO.isPurchaseSaved())		        				
		        		{
			        		 try
		        			{
			        		 
			        		  java.util.Date date = new java.util.Date();
			        	      long t = date.getTime();	        	     
			        	      java.sql.Time time = new java.sql.Time(t);
		        				
		        				
		        				 sql = "update purchaseinfo set "
											+ "invoicenumber=?,"								
											+ "purchasetime=?,"									
											+ "supplierid=?,"
											+ "suppliername=?,"
											+ "transportcharges=?,"
											+ "comments=?,"
											+ "otherexpense=?,"
											+ "purchasetotalamount=?,"											
											+ "totalcgst=?,"
											+ "totalsgst=?,"
											+ "totaligst=?,"
											+ "totalnetamount=? "
											+ "where "
											+ "purchasenumber = '"+purchaseInvoiceInformationDAO.getPurchaseId()+"'";
								 
								 if(preparedStatement!=null)
								 {
									 preparedStatement.close();
									 preparedStatement = null;
								 }
								
								 
								 preparedStatement = connection.prepareStatement(sql);
									
									preparedStatement.setString(1, purchaseInvoiceInformationDAO.getInvoiceNumber());
									preparedStatement.setTime(2, time);
									preparedStatement.setString(3, purchaseInvoiceInformationDAO.getSupplierId());
									preparedStatement.setString(4, purchaseInvoiceInformationDAO.getSupplierName());
									preparedStatement.setFloat(5, purchaseInvoiceInformationDAO.getFrightCharges());
									preparedStatement.setString(6, purchaseInvoiceInformationDAO.getComments());
									preparedStatement.setFloat(7, purchaseInvoiceInformationDAO.getOtherExpense());								
									preparedStatement.setFloat(8, this.getTotalPurchaseAmount());									
									preparedStatement.setFloat(9, this.getTotalCGST());
									preparedStatement.setFloat(10, this.getTotalSGST());
									preparedStatement.setFloat(11, this.getTotalIGST());
									preparedStatement.setFloat(12, this.getTotalNettAmount());							
									
									int k = 1;
								//	preparedStatement.executeUpdate();
									
									if(k>0)
									{
										purchaseInvoiceInformationDAO.setPurchaseId(this.getPurchaseId());							        	
							        	 purchaseInvoiceInformationDAO.setSupplierDetails(this.getSupplierName());
							        	 purchaseInvoiceInformationDAO.setInvoiceNumber(this.getInvoiceNumber());
							        	 purchaseInvoiceInformationDAO.setOtherExpense(this.getOtherExpense());
							        	 purchaseInvoiceInformationDAO.setFrightCharges(this.getFrightCharges());
							        	 purchaseInvoiceInformationDAO.setPurchaseTotalAmount(this.getTotalPurchaseAmount());
							        	 purchaseInvoiceInformationDAO.setInvoiceImage(this.getInvoiceImage());
							        	 purchaseInvoiceInformationDAO.setPurchaseDate(this.getPurchaseDateTime());
							        	 purchaseInvoiceInformationDAO.setTotalCGST(floatTotalCGST);
							        	 purchaseInvoiceInformationDAO.setTotalSGST(floatTotalSGST);
							        	 purchaseInvoiceInformationDAO.setTotalIGST(floatTotalIGST);
							        	 purchaseInvoiceInformationDAO.setTotalNettAmount(floatTotalNettAmount);							        	
							        	 purchaseInvoiceInformationDAO.setPurchaseSaved(false);	        	
							        	 purchaseInvoiceInformationDAO.setAddToStock(this.isAddToStock());
							        	purchaseInvoiceInformationDAO.setPurchaseSaved(false);
							        	purchaseInvoiceInformationDAO.setPurchasedBy(this.getPurchaseBy());
										connection.commit();
										result = "success";
						        		addActionMessage("Product deleted successfully from list !");	
									}
									else
									{
										purchaseProductInfoList.add(dao);
										connection.rollback();
										result = "error";
										addActionError("Product couldn't delete from list !");
										
									}
		        				
		        				
		        			}
			        	 	catch (SQLException e) {
			        	 		
			        	 		result = "error";
			        	 		addActionError("4.Product not removed from list !"+e.getMessage());
			        	 		} 
			        	   		        			
		        			finally
		        			{
		        				if(preparedStatement != null)
		        				{
		        					try {
		        						preparedStatement.close();
		        					} catch (SQLException e) {
		        						
		        					}
		        				}
		        				
		        				if(connection != null)
		        				{
		        					try {
		        						connection.close();
		        					} catch (SQLException e) {
		        						
		        					}
		        				}
		        				
		        				
		        			}
		        		}
			        	 else
			        	 {
			        		 
			        		 purchaseInvoiceInformationDAO.setPurchaseSaved(false);
			        		 result = "success";
				        	 addActionMessage("Product deleted successfully from list !");	
			        	 }
			        	 */
		        		this.getSessionMap().put("purchaseInformation", this.getPurchaseInvoiceInformationDAO());
		        		this.getSessionMap().put("purchaseProductList", this.getPurchaseProductInfoList());
		        		this.getSessionMap().put("deletedProductInfoList", this.getDeletedProductInfoList());
	        		

			    	
			    		taxList = GetListResource.GetTaxList(this.getSessionMap());
			    			
			    	
			        	
			        	unitList = GetListResource.GetUnitList();
			        	
			        	
			        	
		        		
		        		
		        	}
		        	
		        	result  = SUCCESS;
		        	
	        	}
	        	else
	        	{
	        		result = "input";
	        		addActionError("URL Tampered ! Please try again !");
	        	}
	        	}
	        	else
	        	{
	        		result = "error";
	        		addActionError("Something went wrong ! Please try again !");
	        	}
	        	
	        	
	        	if(connection != null)
	        	{
	        		try {
						connection.close();
						connection = null;
					} catch (SQLException e) {
						
					}
	        	}
	        	
	        }
	        
	        
	       
	        return result;
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	

	public String getPurchaseUnit() {
		return purchaseUnit;
	}

	public void setPurchaseUnit(String purchaseUnit) {
		this.purchaseUnit = purchaseUnit;
	}


	public String getTaxId() {
		return taxId;
	}

	public void setTaxId(String taxId) {
		this.taxId = taxId;
	}

	
	public String getPurchaseId() {
		return purchaseId;
	}

	public void setPurchaseId(String purchaseId) {
		this.purchaseId = purchaseId;
	}

	public String getSupplierName() {
		return supplierName;
	}

	public void setSupplierName(String supplierName) {
		this.supplierName = supplierName;
	}

	public String getInvoiceNumber() {
		return invoiceNumber;
	}

	public void setInvoiceNumber(String invoiceNumber) {
		this.invoiceNumber = invoiceNumber;
	}

	public String getComments() {
		return comments;
	}

	public void setComments(String comments) {
		this.comments = comments;
	}

	public File getInvoiceImage() {
		return invoiceImage;
	}

	public void setInvoiceImage(File invoiceImage) {
		this.invoiceImage = invoiceImage;
	}

	public String getInvoiceImageContentType() {
		return invoiceImageContentType;
	}

	public void setInvoiceImageContentType(String invoiceImageContentType) {
		this.invoiceImageContentType = invoiceImageContentType;
	}

	public boolean isAddToStock() {
		return addToStock;
	}

	public void setAddToStock(boolean addToStock) {
		this.addToStock = addToStock;
	}

	public Map<String, String> getTaxList() {
		return taxList;
	}

	public void setTaxList(Map<String, String> taxList) {
		this.taxList = taxList;
	}

	public Map<String, String> getUnitList() {
		return unitList;
	}

	public void setUnitList(Map<String, String> unitList) {
		this.unitList = unitList;
	}

	public PurchaseInvoiceInformationDAO getPurchaseInvoiceInformationDAO() {
		return purchaseInvoiceInformationDAO;
	}

	public void setPurchaseInvoiceInformationDAO(PurchaseInvoiceInformationDAO purchaseInvoiceInformationDAO) {
		this.purchaseInvoiceInformationDAO = purchaseInvoiceInformationDAO;
	}

	public List<PurchaseProductInfoDAO> getPurchaseProductInfoList() {
		return purchaseProductInfoList;
	}

	public void setPurchaseProductInfoList(List<PurchaseProductInfoDAO> purchaseProductInfoList) {
		this.purchaseProductInfoList = purchaseProductInfoList;
	}

	public String getViewPurchaseInvoice() {
		return viewPurchaseInvoice;
	}

	public void setViewPurchaseInvoice(String viewPurchaseInvoice) {
		this.viewPurchaseInvoice = viewPurchaseInvoice;
	}

	
	public Float getTotalPurchaseAmount() {
		return totalPurchaseAmount;
	}

	public void setTotalPurchaseAmount(Float totalPurchaseAmount) {
		this.totalPurchaseAmount = totalPurchaseAmount;
	}

	public Float getTotalNettAmount() {
		return totalNettAmount;
	}

	public void setTotalNettAmount(Float totalNettAmount) {
		this.totalNettAmount = totalNettAmount;
	}

	public Float getTotalCGST() {
		return totalCGST;
	}

	public void setTotalCGST(Float totalCGST) {
		this.totalCGST = totalCGST;
	}

	public Float getTotalSGST() {
		return totalSGST;
	}

	public void setTotalSGST(Float totalSGST) {
		this.totalSGST = totalSGST;
	}

	public Float getTotalIGST() {
		return totalIGST;
	}

	public void setTotalIGST(Float totalIGST) {
		this.totalIGST = totalIGST;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public DecimalFormat getDf() {
		return df;
	}

	public void setDf(DecimalFormat df) {
		this.df = df;
	}
	
	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;  
	}

	public String getProductNameForDelete() {
		return productNameForDelete;
	}

	public void setProductNameForDelete(String productNameForDelete) {
		this.productNameForDelete = productNameForDelete;
	}

	public String getAmountPaid() {
		return amountPaid;
	}

	public void setAmountPaid(String amountPaid) {
		this.amountPaid = amountPaid;
	}

	public Float getAmount() {
		return amount;
	}

	public void setAmount(Float amount) {
		this.amount = amount;
	}

	public Float getQuantity() {
		return quantity;
	}

	public void setQuantity(Float quantity) {
		this.quantity = quantity;
	}

	public Float getPurchaseRate() {
		return purchaseRate;
	}

	public void setPurchaseRate(Float purchaseRate) {
		this.purchaseRate = purchaseRate;
	}

	public Float getFrightCharges() {
		return frightCharges;
	}

	public void setFrightCharges(Float frightCharges) {
		this.frightCharges = frightCharges;
	}

	public Float getOtherExpense() {
		return otherExpense;
	}

	public void setOtherExpense(Float otherExpense) {
		this.otherExpense = otherExpense;
	}

	public Map<String, String> getPaymentTypeList() {
		return paymentTypeList;
	}

	public void setPaymentTypeList(Map<String, String> paymentTypeList) {
		this.paymentTypeList = paymentTypeList;
	}

	public String getPaymentDefaultValue() {
		return paymentDefaultValue;
	}

	public void setPaymentDefaultValue(String paymentDefaultValue) {
		this.paymentDefaultValue = paymentDefaultValue;
	}

	public String getPurchaseBy() {
		return purchaseBy;
	}

	public void setPurchaseBy(String purchaseBy) {
		this.purchaseBy = purchaseBy;
	}

	public String getPurchaseDateTime() {
		return purchaseDateTime;
	}

	public void setPurchaseDateTime(String purchaseDateTime) {
		this.purchaseDateTime = purchaseDateTime;
	}

	public List<PurchaseProductInfoDAO> getDeletedProductInfoList() {
		return deletedProductInfoList;
	}

	public void setDeletedProductInfoList(List<PurchaseProductInfoDAO> deletedProductInfoList) {
		this.deletedProductInfoList = deletedProductInfoList;
	}

	public Map<String, String> getRateTypeList() {
		return rateTypeList;
	}

	public void setRateTypeList(Map<String, String> rateTypeList) {
		this.rateTypeList = rateTypeList;
	}

	public String getRateTyprDefaultValue() {
		return rateTyprDefaultValue;
	}

	public void setRateTyprDefaultValue(String rateTyprDefaultValue) {
		this.rateTyprDefaultValue = rateTyprDefaultValue;
	}

	public Float getDiscount() {
		return discount;
	}

	public void setDiscount(Float discount) {
		this.discount = discount;
	}

	public String getSerialBatchNo() {
		return serialBatchNo;
	}

	public void setSerialBatchNo(String serialBatchNo) {
		this.serialBatchNo = serialBatchNo;
	}

	public Map<String, String> getAccountList() {
		return accountList;
	}

	public void setAccountList(Map<String, String> accountList) {
		this.accountList = accountList;
	}

	public List<String> getPaymentTypeList2() {
		return paymentTypeList2;
	}

	public void setPaymentTypeList2(List<String> paymentTypeList2) {
		this.paymentTypeList2 = paymentTypeList2;
	}

	
	

}
