<%@page language="java" contentType="application/json;charset=UTF-8" pageEncoding="UTF-8"%>
<%@page import="org.apache.log4j.Logger"%>
<%@page import="java.util.Properties"%>
<%@page import="com.truist.app.config.ConfigManager"%>
<%@page import="com.truist.app.properties.AppPropManager"%>
<%@page import="java.io.InputStream"%>
<%@page import="javax.servlet.ServletOutputStream"%>
<%@page import="javax.servlet.ServletContext"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.PrintWriter"%>
<%@page import="java.io.File"%>
<%@page import="java.io.OutputStream"%>

<% 
		Logger logger = Logger.getLogger("Backend");
		String action = request.getParameter("action");
		
		String envType = System.getProperty("envType");
		StringBuilder fileLocation = new StringBuilder(System.getProperty("backendPropertiesLocation"));
		
		logger.debug("ReloadProperties.doGet: Environment Type: ["+envType+"]");
		logger.debug("ReloadProperties.doGet: application.properties location path: ["+fileLocation.toString()+"]");
		fileLocation.append("/");
		fileLocation.append(envType);
		fileLocation.append("/");
		fileLocation.append("application.properties");  
		
		
		if (action.equals("reload")) {
			try {
				AppPropManager
				.setAppProperties(ConfigManager.loadAppProperties(getServletContext(), fileLocation.toString()));
			}
			catch (IllegalStateException ise) {
				throw new ServletException("ReloadProperties.doGet: IllegalStateException - Error loading the backend properties file: ["+ise+"].");
			}
			catch (Exception mse) {
				throw new ServletException("ReloadProperties.doGet: MissingConfigurationException - Error loading the backend properties file: ["+mse+"].");
			} // end try/catch
		}
		
		if (action.equals("display")) {
			try {
				File downloadFile = new File(fileLocation.toString());
		        FileInputStream inStream = new FileInputStream(downloadFile);
		        ServletContext context = getServletContext();
		        // gets MIME type of the file
		        String mimeType = context.getMimeType(fileLocation.toString());
		        if (mimeType == null) {        
		            // set to binary type if MIME mapping not found
		            mimeType = "application/octet-stream";
		        }
		        
		        // obtains response's output stream
		        OutputStream outStream = response.getOutputStream();
		         
		        byte[] buffer = new byte[4096];
		        int bytesRead = -1;
		         
		        while ((bytesRead = inStream.read(buffer)) != -1) {
		            outStream.write(buffer, 0, bytesRead);
		        }
		         
		        inStream.close();
		        outStream.close(); 
				logger.debug("File downloaded at client successfully");
			} catch(Exception e) {
				logger.error("!!Exception occured during file display!!");
				e.printStackTrace();
			}
		}

%>
