package com.reallinkbilling.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;

import org.apache.struts2.dispatcher.SessionMap;

import com.reallinkbilling.db.GetDBConnection;

public class GetLastBillNumber {
	public static String getLastBillNumber(String billType, SessionMap<String, Object> sessionMap)
	{
		String lastBillNumber = "";
		
		Connection connection = null;
		PreparedStatement preparedStatement= null;
		ResultSet  resultSet = null;
		
		String sql = "";
		String db = (String) sessionMap.get("db");
	
		
		try
		{
			String shopId = (String) sessionMap.get("shopId");
    		String shopCode = (String) sessionMap.get("shopCode");
    		
    		
			connection = GetDBConnection.getDBConnection(db);
			
			ArrayList <Integer> billNumbers = new ArrayList<Integer>();
			
			String fianacialYear = (String) sessionMap.get("financialyearstartdate");
    		
			

			sql = "SELECT "
					+ "bill_number "
					+ "FROM "
					+ "shop_bill_info_master "
					+ "WHERE "
					+ "bill_type = ? "
					+ "AND "
					+ "shop_id = ? "
					+ "AND "
					+ "shop_code= ? "
					+ "AND "
					+ "bill_date >= ?";
			
			preparedStatement = connection.prepareStatement(sql);
			
			preparedStatement.setString(1, billType);
			preparedStatement.setString(2, shopId);
			preparedStatement.setString(3, shopCode);
			preparedStatement.setString(4, fianacialYear);
			
		//	System.out.println(preparedStatement.toString());
			
			resultSet = preparedStatement.executeQuery();
			int newBillNumber = 0;
			while(resultSet.next())
			{
				billNumbers.add(resultSet.getInt(1));						
			}
			
		
			Collections.sort(billNumbers);
			

			if(billNumbers.size() > 0)
			{
				 
				 newBillNumber = billNumbers.get(billNumbers.size()-1);
			}
			
			lastBillNumber = ""+newBillNumber;
			
		}catch (SQLException e) {
	 		//e.printStackTrace();
			lastBillNumber = "NA";
	 		
	 	}
		catch (Exception e) {
			//e.printStackTrace();
			lastBillNumber = "NA";
		}
		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 lastBillNumber;
		
		
	}

}
