package com.reallinkbilling.add;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
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.FinishedProductInfoDAO;
import com.reallinkbilling.db.GetDBConnection;

public class SaveFinishedProductDetailsList extends ActionSupport implements SessionAware {

	/**
	 * 
	 */
	private static final long serialVersionUID = -765646958895461503L;

	private HttpSession session;
	private SessionMap<String,Object> sessionMap; 
	private List<FinishedProductInfoDAO> finishedProductInfoList ;
	
	@SuppressWarnings("unchecked")
	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 fullUserName = (String) this.getSessionMap().get("userFullName");
	        	
	        	String splitUserName [] = new String[5];
	        	
	        	String userName = "";
	        	try
	        	{
	        		splitUserName = fullUserName.split(" ");
	        		userName = splitUserName[0];
	        		
	        	}catch(Exception e)
	        	{
	        		userName =fullUserName;
	        	}
	        	
	        	
	        	String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    		
			
	    		this.setFinishedProductInfoList((List<FinishedProductInfoDAO>) this.getSessionMap().get("finishedProductInfoList"));
	        	
	    	
	    		String finishedProductId = "";
	    		String finishedProductCode = "";
	    		
	    		for(FinishedProductInfoDAO dao : this.getFinishedProductInfoList())
	        	{
	    			finishedProductId = dao.getFinishedProductId();
	    			finishedProductCode = dao.getFinishedProductCode();
	        	}
	    	   	
		        Connection connection = null;
				PreparedStatement preparedStatement= null;
				ResultSet resultSet = null;
				
				String sql = "";
				String db = (String) this.getSessionMap().get("db");
				
				
				
				try
	        	{

		        	Date d = new Date();
		        	SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
		        	
		        	String date = dateFormat.format(d);
		        	
		        	int entryId = 1;
	        		
				connection = GetDBConnection.getDBConnection(db);
	        	connection.setAutoCommit(false);
	        	
	        	boolean isFinishedProductAdded = false;
	        	
	        	sql = "SELECT * FROM "
	        			+ "shop_finished_product_details_master "
	        			+ "WHERE "
	        			+ "shop_id = ? "
	        			+ "AND "
	        			+ "shop_code = ? "
	        			+ "AND "
	        			+ "finished_product_id = ? "
	        			+ "AND "
	        			+ "finished_product_short_code = ?";
	        	
	        	preparedStatement = connection.prepareStatement(sql);
	        	
	        	preparedStatement.setString(1, shopId);
	        	preparedStatement.setString(2, shopCode);
	        	preparedStatement.setString(3, finishedProductId);
	        	preparedStatement.setString(4, finishedProductCode);
	        	
	        	resultSet = preparedStatement.executeQuery();
	        	
	        	if(resultSet.next())
	        	{
	        		isFinishedProductAdded = true;
	        	}
	        	

	        	if(resultSet != null)
	        	{
	        		resultSet.close();
	        		resultSet = null;
	        	}
	        	
	        	if(preparedStatement != null)
	        	{
	        		preparedStatement.close();
	        		preparedStatement = null;
	        		
	        	}
	        	
	        	
	        	if(isFinishedProductAdded)
	        	{
	        		PreparedStatement deletePSMT = null;
	        	
	        		sql = "DELETE "
	        				+ "FROM "
	        				+ "shop_finished_product_details_master "
	        				+ "WHERE "
		        			+ "shop_id = ? "
		        			+ "AND "
		        			+ "shop_code = ? "
		        			+ "AND "
		        			+ "finished_product_id = ? "
		        			+ "AND "
		        			+ "finished_product_short_code = ?";
	        		
	        		deletePSMT = connection.prepareStatement(sql);
		        	
	        		deletePSMT.setInt(1, Integer.parseInt(shopId));
	        		deletePSMT.setString(2, shopCode);
	        		deletePSMT.setInt(3, Integer.parseInt(finishedProductId));
	        		deletePSMT.setString(4, finishedProductCode);
		       	
		        	int k = deletePSMT.executeUpdate();
		        	
		        	if(deletePSMT != null)
		        	{
		        		deletePSMT.close();
		        		deletePSMT = null;
		        	}
		        	
		        	
	        	}

	        
	        	
	        
	        	
	        	
	        	sql = "SELECT "
	        			+ "entry_id "
	        			+ "FROM "
	        			+ "shop_finished_product_details_master "
	        			+ "ORDER BY entry_id DESC LIMIT 1";
	        	
	        	preparedStatement = connection.prepareStatement(sql);
	        	
	        	resultSet = preparedStatement.executeQuery();
	        	
	        	if(resultSet.next())
	        	{
	        		entryId = resultSet.getInt(1);
	        	}
	        	
	        	if(resultSet != null)
	        	{
	        		resultSet.close();
	        		resultSet = null;
	        	}
	        	
	        	if(preparedStatement != null)
	        	{
	        		preparedStatement.close();
	        		preparedStatement = null;
	        		
	        	}
	        	sql = "INSERT INTO "
	        			+ "shop_finished_product_details_master "
	        			+ "(entry_id,"
	        			+ "date_added,"
	        			+ "shop_id,"
	        			+ "shop_code,"
	        			+ "finished_product_id,"
	        			+ "finished_product_name_eng,"
	        			+ "finished_product_short_code,"
	        			+ "product_id,"
	        			+ "product_name_eng,"
	        			+ "product_short_code,"
	        			+ "product_quantity_required,"
	        			+ "entry_by) "
	        			+ "VALUES "
	        			+ "(?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?)";
	        	
	        	preparedStatement = connection.prepareStatement(sql);
	        	for(FinishedProductInfoDAO dao : this.getFinishedProductInfoList())
	        	{
	        		entryId = entryId + 1;
	        		preparedStatement.setInt(1, entryId);
	        		preparedStatement.setString(2, date);
	        		preparedStatement.setString(3, shopId);
	        		preparedStatement.setString(4, shopCode);
	        		preparedStatement.setString(5, dao.getFinishedProductId());
	        		preparedStatement.setString(6, dao.getFinishedProductName());
	        		preparedStatement.setString(7, dao.getFinishedProductCode());
	        		preparedStatement.setString(8, dao.getProductId());
	        		preparedStatement.setString(9, dao.getProductName());
	        		preparedStatement.setString(10, dao.getProductCode());
	        		preparedStatement.setFloat(11, dao.getProductQuantity());
	        		preparedStatement.setString(12, userName);	        	
	        		preparedStatement.addBatch();
	        	}
	        	
	        	int [] rowInserted = preparedStatement.executeBatch();
	        	
	        	if(this.getFinishedProductInfoList().size() == rowInserted.length)
	        	{
	        		result = SUCCESS;
	        		connection.commit();
	        		addActionMessage("Finished product details added successfully!");
	        	}
	        	else
	        	{
	        		
	        		result = ERROR;
	        		connection.rollback();
	        		addActionError("Finished product details not added! Please try again!");
	        	}
	        	
	        	
	        	}catch (SQLException e) {
	        		//e.printStackTrace();
	        		result = ERROR;
	        		addActionError("Finished Product Details Not Added! "+e.getErrorCode()+"|| "+e.getMessage());
	        		
	        	} catch (IOException e) {
	        		result = ERROR;
	        		addActionError("Finished Product Details Not Added! "+e.getMessage());
					
				}finally {
					if(resultSet != null)
	   				{
	   					try {resultSet.close();}catch(SQLException sqe){}   					
	   				}
					if(preparedStatement != null)
					{
						try {preparedStatement.close();} catch (SQLException e) {}
					}
					if(connection != null)
					{
						
						try {connection.close();}catch (SQLException e) {}
					}
					
	        	}
	        	
	        	
	        }
	        
	        return result; 
}
	
	
	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 HttpSession getSession() {
		return session;
	}
	public void setSession(HttpSession session) {
		this.session = session;
	}


	public List<FinishedProductInfoDAO> getFinishedProductInfoList() {
		return finishedProductInfoList;
	}


	public void setFinishedProductInfoList(List<FinishedProductInfoDAO> finishedProductInfoList) {
		this.finishedProductInfoList = finishedProductInfoList;
	}


	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	
	
}
