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 GetLastChallanNumber {
	
	public static String getLastChallanNumber(SessionMap<String, Object> sessionMap)
	{
		String lastChallanNumber = "";
		
		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> challanNumbers = new ArrayList<Integer>();
			
			String fianacialYear = (String) sessionMap.get("financialyearstartdate");
    		
			

			sql = "SELECT "
					+ "challan_number "
					+ "FROM "
					+ "shop_challan_info_master "
					+ "WHERE "
					+ "shop_id = ? "
					+ "AND "
					+ "shop_code= ? "
					+ "AND "
					+ "challan_date >= ?";
			
			preparedStatement = connection.prepareStatement(sql);
			
			preparedStatement.setString(1, shopId);
			preparedStatement.setString(2, shopCode);
			preparedStatement.setString(3, fianacialYear);
			
		//	System.out.println(preparedStatement.toString());
			
			resultSet = preparedStatement.executeQuery();
			int newChallanNumber = 0;
			while(resultSet.next())
			{
				challanNumbers.add(resultSet.getInt(1));						
			}
			
		
			Collections.sort(challanNumbers);
			

			if(challanNumbers.size() > 0)
			{
				 
				newChallanNumber = challanNumbers.get(challanNumbers.size()-1);
			}
			
			lastChallanNumber = ""+newChallanNumber;
			
		}catch (SQLException e) {
	 		//e.printStackTrace();
			lastChallanNumber = "NA";
	 		
	 	}
		catch (Exception e) {
			//e.printStackTrace();
			lastChallanNumber = "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 lastChallanNumber;
		
		
	}

}
