package ibase.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.json.JSONObject;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import ibase.utility.BaseLogger;
import ibase.utility.CommonConstants;
import ibase.utility.E12GenericUtility;
import ibase.webitm.utility.ITMException;

public class WelcomeMsgServlet extends HttpServlet{
	//Added By Suraj on 18-11-2016 [ For Calendar Date format issue on server startup]Start
	ServletContext servletContext = null;
	ServletConfig servletConfig = null;
	//Added By Suraj on 18-11-2016 [ For Calendar Date format issue on server startup]End
	protected void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException
	{
		//Added By Prajyot on 17MAY2013 [ As per Danish Sir for Russian Server Issue]
		request.setCharacterEncoding( CommonConstants.ENCODING );
		response.setContentType("application/x-www-form-urlencoded; charset="+CommonConstants.ENCODING);
		BaseLogger.log("2",null,null,"inside doGet session 89");
		response.setHeader("Access-Control-Allow-Origin","*");
		response.setHeader("Access-Control-Allow-Headers","content-type,authorization");
		response.setHeader("Access-Control-Allow-Credentials","true");
		response.setHeader("Set-Cookie", "JSESSIONID="+request.getSession().getId()+"; HttpOnly; SameSite=none; secure");
		request.getSession().setAttribute("NameInSession", "DANISH");
		BaseLogger.log("2",null,null,"95 inside doGet session id :"+request.getSession().getId());
		doPost( request, response );
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException
	{
		//Added By Prajyot on 17MAY2013 [ As per Danish Sir for Russian Server Issue]
		//Added By Suraj on 14-11-2016 [To get servlet context object ]
		servletConfig = getServletConfig();
		servletContext = servletConfig.getServletContext();
		request.setCharacterEncoding( CommonConstants.ENCODING );
		response.setContentType("application/x-www-form-urlencoded; charset="+CommonConstants.ENCODING);

		BaseLogger.log("2",null,null,"*** WelcomeMsgServlet Called ***");
		String action = request.getParameter("action");
		if("WELCOMEMSG".equals(action)){
			ibase.utility.UserInfoBean usrInfo = ( ibase.utility.UserInfoBean )request.getSession().getAttribute( "USER_INFO" );
			String welcomeMsg = "";
			if(usrInfo != null)
			{
				//Add by Dnyaneshwar 28/DEC/2012 [Add new two values are emp. name & emp code ] Start
				//welcomeMsg = usrInfo.getDesignation()+":"+usrInfo.getDivision()+":"+usrInfo.getSiteCode()+":"+usrInfo.getDateJoin();
				welcomeMsg = usrInfo.getDesignation()+":"+usrInfo.getDivision()+":"+usrInfo.getSiteCode()+":"+usrInfo.getDateJoin()+":"+usrInfo.getEmpName()+":"+usrInfo.getEmpCode();
				//Add by Dnyaneshwar 28/DEC/2012 [Add new two values are emp. name & emp code ] Start
			}
			//Added by Ajinkya Darvesh on 14/07/2017 [For passing session expired string to 500.html] [START]
			else
			{
				//Changed by Sandeep S. on 19-JAN-17 [To check session exist or not for same user on same or on another machine] Start
				//request.getSession().invalidate();
				//Changed by Sandeep S. on 19-JAN-17 [To check session exist or not for same user on same or on another machine] End
				//Changes made by Pratheek on 14-12-18[to show new descritpion and title of SESSION_EXPIRED on alert]-Start
				//welcomeMsg="SESSION_EXPIRED";
				welcomeMsg="Session Expired";
				//Changes made by Pratheek on 14-12-18[to show new descritpion and title of SESSION_EXPIRED on alert]-End
			}
			//Added by Ajinkya Darvesh on 14/07/2017 [For passing session expired string to 500.html] [END]
			OutputStream OutputString=response.getOutputStream();
			OutputString.write(welcomeMsg.getBytes());
			OutputString.flush();
			OutputString.close();
		}
		//Added by Harshada 26th Nov 2012 [User connections on login]
		else if("GETDISPLAYDETAILS".equalsIgnoreCase(action))
		{
			try
			{
				String dispDetails = getDisplayDetails(request);

				PrintWriter writer = response.getWriter();

				//Added by Dnyaneshwar Chavan on 24-OCT-13 [CO3ASUN005] [ Resolved the issue of when response in Russian language or etc.  ] START
				//response.setContentType("text/html");
		        response.setContentType( "text/html; charset="+CommonConstants.ENCODING );
		        //Added by Dnyaneshwar Chavan on 24-OCT-13 [CO3ASUN005] [ Resolved the issue of when response in Russian language or etc.  ] END

				writer.write( dispDetails );
				writer.flush();
				writer.close();

			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			}
		}
		//Added by Prajyot [W15HMIT002 - GPS_ENFORCED Implementation to pass CommonConstants params ] Start
		else if("GET_SERVER_INFO".equalsIgnoreCase(action))
		{
			try
			{
				//Changed By Suraj on 14-11-2016 [ To set date formats from DateFormat.xml on server startup ]Start
				BaseLogger.log("3",null,null,"APPL_DATE_FORMAT ["+CommonConstants.APPL_DATE_FORMAT+"] DISP_DATE_FORMAT ["+CommonConstants.DISP_DATE_FORMAT+"]");
				JSONObject jsonObj = new JSONObject();
				if( "".equals(CommonConstants.APPL_DATE_FORMAT) && this.servletContext != null )
				{
					CommonConstants.setAPPLICATION_CONTEXT(this.servletContext.getRealPath("/"));
					//Commented by Sagar B. for Geo position related changes for multi tenancy on [11Jan18]
					//jsonObj.put("GPS_ENABLED", CommonConstants.GEOPOS_ENABLE);
					//jsonObj.put("GPS_ENFORCED", CommonConstants.GPS_ENFORCED);
					jsonObj.put("APPL_DATE_FORMAT", CommonConstants.APPL_DATE_FORMAT);
					jsonObj.put("DISP_DATE_FORMAT", CommonConstants.DISP_DATE_FORMAT);
					jsonObj.put("APPL_DATETIME_FORMAT", CommonConstants.APPL_DATETIME_FORMAT);
					jsonObj.put("DISP_DATETIME_FORMAT", CommonConstants.DISP_DATETIME_FORMAT);
//					jsonObj.put("FRAMEWORK_VERSION", CommonConstants.FRAMEWORK_VERSION);
				}
				else
				{
					//Commented by Sagar B. for Geo position related changes for multi tenancy on [11Jan18]
					//jsonObj.put("GPS_ENABLED", CommonConstants.GEOPOS_ENABLE);
					//jsonObj.put("GPS_ENFORCED", CommonConstants.GPS_ENFORCED);
					jsonObj.put("APPL_DATE_FORMAT", CommonConstants.APPL_DATE_FORMAT);
					jsonObj.put("DISP_DATE_FORMAT", CommonConstants.DISP_DATE_FORMAT);
					jsonObj.put("APPL_DATETIME_FORMAT", CommonConstants.APPL_DATETIME_FORMAT);
					jsonObj.put("DISP_DATETIME_FORMAT", CommonConstants.DISP_DATETIME_FORMAT);
//					jsonObj.put("FRAMEWORK_VERSION", CommonConstants.FRAMEWORK_VERSION);
				}
				//Changed By Suraj on 14-11-2016 [ To set date formats from DateFormat.xml on server startup ]End
				BaseLogger.log("3",null,null,"jsonObj :==>" + jsonObj);

				JSONObject respJSONObj = new JSONObject();
				respJSONObj.put("SERVER_INFO", jsonObj);
				BaseLogger.log("9",null,null,"respJSONObj :==>" + respJSONObj);

				PrintWriter writer = response.getWriter();
		        response.setContentType( "text/plain; charset="+CommonConstants.ENCODING );
				writer.write( respJSONObj.toString() );
				writer.flush();
				writer.close();
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		//Added by Prajyot [W15HMIT002 - GPS_ENFORCED Implementation to pass CommonConstants params ] End

	}
	/**
	 * Gets "display-name" and "description"<br>
	 * from JbossHome/ibase.ear/META-INF/application.xml
	 */
	//Changes by Prajyot 09JAN2014 [Access displayName and description from application.xml] Start
 	private String getDisplayDetails(HttpServletRequest request) throws ParserConfigurationException, SAXException, IOException
 	{
		String displayVal = "";
		String dispNameTag = request.getParameter("displayName");
// 		String descTag = request.getParameter("description");
//
//		String fileName = CommonConstants.APPLICATION_CONTEXT;
//		String separator = System.getProperty("file.separator");
//		String applFilePath = null;
//
//		BaseLogger.log("9",null,null,"Called getDisplayValues():: " +fileName);
//		if (fileName.contains(".war"))
//		{
//			int lastSeparatorIndex = fileName.lastIndexOf(separator	+ "ibase.war");
//			if (lastSeparatorIndex == -1)
//			{
//				applFilePath = fileName;
//			}
//			else
//			{
//				applFilePath = fileName.substring(0, lastSeparatorIndex + 1) + "META-INF"+separator+"application.xml";
//			}
//		}
//		BaseLogger.log("9",null,null,"Called getDisplayValues() from:: " + applFilePath);
//		Document doc = null;
//		File fXmlFile = new File(applFilePath);
//		try
//		{
//			doc = new E12GenericUtility().parseFile(fXmlFile);
//			NodeList applNodeList = doc.getElementsByTagName("application").item(0).getChildNodes();
//			displayVal = getColumnValueFromNodeList(dispNameTag, applNodeList);
//			BaseLogger.log("9",null,null,"display Details for user connections: " + dispNameTag + ":" + displayVal);
//			displayVal = displayVal + "," + getColumnValueFromNodeList(descTag, applNodeList);;
//			BaseLogger.log("9",null,null,"display Details for user connections: " + descTag + ":" + displayVal);
//		}
//		catch (Exception e)
//		{
//			BaseLogger.log("9",null,null,"Exception in parsing file: "+e.getMessage());
//			e.printStackTrace();
//		}
		//Commented and Added by Sagar B. to show descr from enterprise table instead Application.xml in slide menu panel[18-Sep-18]START
		try
		{
			ibase.utility.UserInfoBean usrInfo = ( ibase.utility.UserInfoBean )request.getSession().getAttribute( "USER_INFO" );
			if( usrInfo != null )
			{
				if( E12GenericUtility.checkNull( usrInfo.getEnterpriseDescr() ).length() > 0 )
				{
					displayVal = dispNameTag + "," + E12GenericUtility.checkNull( usrInfo.getEnterpriseDescr() );
				}
				else
				{
					displayVal = dispNameTag + ", ";
				}
				BaseLogger.log("3",null,null,"displayVal::["+displayVal+"]");

			}
		}
		catch (Exception e)
		{
			BaseLogger.log("0",null,null,"Exception in getDisplayDetails: "+e.getMessage());
		}
		//Commented and Added by Sagar B. to show descr from enterprise table instead Application.xml in slide menu panel[18-Sep-18]END
 		return displayVal;
 	}

	private String getColumnValueFromNodeList( String colName, NodeList applNodeList )throws ITMException
 	{
		String colValue = null;
		try
		{
			int noOfChilds = applNodeList.getLength();
			for(int colCtr = 0; colCtr < noOfChilds; colCtr++)
			{
				Node colNode = applNodeList.item(colCtr);
				if(colNode != null && colNode.getNodeType() == Node.ELEMENT_NODE)
				{
					if(colNode.getNodeName().equals(colName))
					{
						if(colNode.getFirstChild() != null)
						{
							colValue = colNode.getFirstChild().getNodeValue();
						}
						else
						{
							colValue = colNode.getNodeValue();
						}
						break;
					}
				}
			}
		}
		catch(Exception e)
		{
			throw new ITMException(e);
		}
		BaseLogger.log("2",null,null,"colValue[" + colValue + "]");
		return colValue;
 	}

	/*
 	private String getDisplayDetails(HttpServletRequest request) throws ParserConfigurationException, SAXException, IOException
 	{
 		String displayNameTag = request.getParameter("displayName");
 		String descTag = request.getParameter("description");
 		String displayVal = GenericUtility.getInstance().getDisplayValues(displayNameTag)+","+GenericUtility.getInstance().getDisplayValues(descTag);
 		return displayVal;
 	}
 	//END Harshada 26th Nov 2012 [User connections on login]
	*/
	//Changes by Prajyot 09JAN2014 [Access displayName and description from application.xml] Ends
}
