package com.reallinkbilling.interceptor;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Map;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.reallinkbilling.db.GetDBConnection;

public class SessionInterceptor extends AbstractInterceptor implements SessionAware {
	  /**
	 * 
	 */
	private static final long serialVersionUID = 6682200684597421360L;
	private SessionMap<String,Object> sessionMap; 
	@Override
	  public String intercept(ActionInvocation invocation) throws Exception {
		System.out.print("Session Timout");
		setSession(sessionMap);
		
		 if(sessionMap!=null){  
			 System.out.println("In Invalidate Session !!!");
		        
		        
		    	Connection connection = null;
				PreparedStatement preparedStatement= null;
				
				String sql = "";
				String userName = (String) sessionMap.get("username");
				
				String schema = "";
				schema = "rlbilling";
				
				try {
					System.out.print("Session Timout");
					
					connection = new GetDBConnection().getDBConnection(schema);
					if(connection != null)
					{
						
						 sql= "update users "
							  		+ "set accountstatus='UNLOCKED' where username='"+userName.trim()+"'";
							  preparedStatement = connection.prepareStatement(sql);
							  preparedStatement.executeUpdate();
							 
					}
				} catch (SQLException e) {
					
				
				}catch (IOException e) {
					
				}
				finally
				{
					if(preparedStatement != null)
					{
						try {
							
							preparedStatement.close();
						} catch (SQLException e) {
							
						}
					}
					if(connection != null)
					{
						try {
							
							connection.close();
						} catch (SQLException e) {
							
							e.printStackTrace();
						}
					}
					
					 sessionMap.invalidate();
				
			}
		    }  
		
		
		Map<String,Object> session = invocation.getInvocationContext().getSession();
	      if(session.isEmpty())
	          return "session"; // session is empty/expired
	      
	      
	      return invocation.invoke();
	  }

	public void setSession(Map<String, Object> map) {
		// TODO Auto-generated method stub
		 sessionMap=(SessionMap<String, Object>)map;  
		
	}

}