package com.bankaudit.report.v3.rest.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.bankaudit.constants.BankAuditConstant;
// import com.bankaudit.report.v3.service.AuditBookReportServiceImplV3Thread;
import com.bankaudit.report.v3.service.AuditBookReportServiceV3;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;


/**
 * This controller includes audit plan process like
 * get Branch units,schedule dates,team and validation.  
 * 
 * @author narendar.burada
 * @version 1.0
 * @since 2014-03-31
 */



@RestController

@RequestMapping("/api/auditReportV3")
public class ReportBookControllerV3 { 
	
	@Autowired
	AuditBookReportServiceV3 auditBookReportServiceV3;
	
	//@Autowired
	//AuditBookReportServiceV3 auditBookReportServiceV3Thread;
	 
	static final Logger logger = Logger.getLogger(ReportBookControllerV3.class);
 
	
@RequestMapping(value = "/generateAuditIRReportV3", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	void  generateAuditIRReportV3(
			@RequestParam("legalEntityCode") int legalEntityCode,
			@RequestParam(value="auditId",required=true) String auditId,
		 	@RequestParam(value="auditTypeCode",required=true) String auditTypeCode,
		 	@RequestParam(value="userId",required=true) String userId,
			@RequestParam(value="reportLanguage", required=true) String reportLanguage, 
			HttpServletRequest request,      HttpServletResponse response){
		 	
		logger.info("generateAuditBookReport .. "+legalEntityCode + " :: "+ auditId );
		if((legalEntityCode>=0) && (auditId!=null && !BankAuditUtil.isEmptyString(auditId)) ){ 
			try { 				
 
				String logoPath =  request.getServletContext().getRealPath("/assets/ir_logo.png"); 
			    Map<String, Object> params = new HashMap<String, Object>();					
			    params.put("logo", logoPath); 
			    String uploadPath = auditBookReportServiceV3.generatePDFReport(params, legalEntityCode, auditId, auditTypeCode, userId, false, "", "", "", reportLanguage);
					
				if(uploadPath!=null){
			    	 File file=new File(uploadPath);
			    	 FileInputStream inputStream = new FileInputStream(file); 		    	    
					 String mimeType ="application/pdf";  						 
		             response.setContentType(mimeType); 
		             String headerKey = "Content-Disposition";
		             String headerValue = String.format("attachment; filename=\"%s\"",file.getName());
		             response.setHeader(headerKey, headerValue); 
		             OutputStream outStream = response.getOutputStream();
		            
		             byte[] buffer = new byte[4096*4096]; // 4096-> bufferSize
		             int bytesRead = -1;
		       
		             while ((bytesRead = inputStream.read(buffer)) != -1) {
		                 outStream.write(buffer, 0, bytesRead);
		             }
		             inputStream.close();
		             outStream.close();                
		    	}else {
					 response.getWriter().print("Document not exist");
				}			     
			} catch (Exception e) {
				e.printStackTrace();					
			}
		}		 
	} 
	
	
@RequestMapping(value = "/generateAuditIRReportFinal", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus  generateAuditIRReportFinal(
			@RequestParam("legalEntityCode") int legalEntityCode,
			@RequestParam(value="auditId",required=true) String auditId,
		 	@RequestParam(value="auditTypeCode",required=true) String auditTypeCode,
		 	@RequestParam(value="planId",required=true) String planId, 
		 	@RequestParam(value="unitId",required=true) String unitId,  
		 	@RequestParam(value="userId",required=true) String userId,
			@RequestParam(value="reportLanguage", required=true) String reportLanguage, 
			HttpServletRequest request,      HttpServletResponse response){
		 	
		logger.info("generateAuditBookReport .. "+legalEntityCode + " :: "+ auditId );
		ServiceStatus serviceStatus=new ServiceStatus();	
		if((legalEntityCode>=0) && (auditId!=null && !BankAuditUtil.isEmptyString(auditId)) ){ 
			try { 				
 
				String logoPath =  request.getServletContext().getRealPath("/assets/ir_logo.png"); 
			    Map<String, Object> params = new HashMap<String, Object>();					
			    params.put("logo", logoPath); 
			    String status = auditBookReportServiceV3.generatePDFReport(params, legalEntityCode, auditId, auditTypeCode, userId, true, planId, unitId,
			    		BankAuditConstant.REPORT_CODE_IR, reportLanguage);
					
				if(status.equalsIgnoreCase(BankAuditConstant.SUCCESS)){
					serviceStatus.setMessage("success");
					serviceStatus.setStatus("success");
		    	}else {
		    		serviceStatus.setMessage("Failed to finalize the Inspection report");
					serviceStatus.setStatus("failed");
				}			     
			} catch (Exception e) {
				e.printStackTrace();	
				serviceStatus.setMessage("failed");
				serviceStatus.setStatus("failed");
			}
		}		 
		return serviceStatus;
	} 
	
	
@RequestMapping(value = "/generateAuditCRReportV3", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	void  generateAuditIRReportCRV3(
			@RequestParam("legalEntityCode") int legalEntityCode,
			@RequestParam(value="auditId",required=true) String auditId,
		 	@RequestParam(value="auditTypeCode",required=true) String auditTypeCode,
		 	@RequestParam(value="userId",required=true) String userId,
			@RequestParam(value="reportLanguage", required=true) String reportLanguage, 
			@RequestParam(value="actionType", required=false) String actionType,
			@RequestParam(value="role", required=true)  String role,
			HttpServletRequest request,      HttpServletResponse response){
		 	
		logger.info("generateAuditIRReportCRV3 .. "+legalEntityCode + " :: "+ auditId );
		if((legalEntityCode>=0) && (auditId!=null && !BankAuditUtil.isEmptyString(auditId)) ){ 
			try { 				
 
				String logoPath =  request.getServletContext().getRealPath("/assets/ir_logo.png"); 
			    Map<String, Object> params = new HashMap<String, Object>();					
			    params.put("logo", logoPath); 
			    String uploadPath = auditBookReportServiceV3.generatePDFReportCR(params, legalEntityCode, auditId, auditTypeCode, userId, false, "", "", "", reportLanguage,
			    		actionType, role);
					
				if(uploadPath!=null){
			    	 File file=new File(uploadPath);
			    	 FileInputStream inputStream = new FileInputStream(file); 		    	    
					 String mimeType ="application/pdf";  						 
		             response.setContentType(mimeType); 
		             String headerKey = "Content-Disposition";
		             String headerValue = String.format("attachment; filename=\"%s\"",file.getName());
		             response.setHeader(headerKey, headerValue); 
		             OutputStream outStream = response.getOutputStream();
		            
		             byte[] buffer = new byte[4096*4096]; // 4096-> bufferSize
		             int bytesRead = -1;
		       
		             while ((bytesRead = inputStream.read(buffer)) != -1) {
		                 outStream.write(buffer, 0, bytesRead);
		             }
		             inputStream.close();
		             outStream.close();                
		    	}else {
					 response.getWriter().print("Document not exist");
				}			     
			} catch (Exception e) {
				e.printStackTrace();					
			}
		}		 
	} 
	
	
@RequestMapping(value = "/generateAuditCRReportFinal", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus  generateAuditCRReportFinal(
			@RequestParam("legalEntityCode") int legalEntityCode,
			@RequestParam(value="auditId",required=true) String auditId,
		 	@RequestParam(value="auditTypeCode",required=true) String auditTypeCode,
		 	@RequestParam(value="planId",required=true) String planId, 
		 	@RequestParam(value="unitId",required=true) String unitId,  
		 	@RequestParam(value="userId",required=true) String userId,
			@RequestParam(value="reportLanguage", required=true) String reportLanguage, 
			@RequestParam(value="actionType", required=false) String actionType,
			@RequestParam(value="role", required=true)  String role,
			HttpServletRequest request,      HttpServletResponse response){
		 	
		logger.info("generateAuditBookReport .. "+legalEntityCode + " :: "+ auditId );
		ServiceStatus serviceStatus=new ServiceStatus();	
		if((legalEntityCode>=0) && (auditId!=null && !BankAuditUtil.isEmptyString(auditId)) ){ 
			try { 				
 
				String logoPath =  request.getServletContext().getRealPath("/assets/ir_logo.png"); 
			    Map<String, Object> params = new HashMap<String, Object>();					
			    params.put("logo", logoPath); 
			    String status = auditBookReportServiceV3.generatePDFReportCR(params, legalEntityCode, auditId, auditTypeCode, userId, true, planId, unitId,
			    		BankAuditConstant.REPORT_CODE_CR, reportLanguage, actionType, role);
					
			    if(status.equalsIgnoreCase(BankAuditConstant.SUCCESS)){
					serviceStatus.setMessage("success");
					serviceStatus.setStatus("success");
		    	}else {
		    		serviceStatus.setMessage("Failed to finalize the Compliance report");
					serviceStatus.setStatus("failed");
				}			     
			} catch (Exception e) {
				e.printStackTrace();	
				serviceStatus.setMessage("failed");
				serviceStatus.setStatus("failed");
			}
		}		 
		return serviceStatus;
	}
	
	
@RequestMapping(value = "/generateAuditSRReportV3", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	void  generateAuditIRReportSRV3(
			@RequestParam("legalEntityCode") int legalEntityCode,
			@RequestParam(value="auditId",required=true) String auditId,
		 	@RequestParam(value="auditTypeCode",required=true) String auditTypeCode,
		 	@RequestParam(value="userId",required=true) String userId,
			@RequestParam(value="reportLanguage", required=true) String reportLanguage, 
			@RequestParam(value="actionType", required=false) String actionType,
			@RequestParam(value="role", required=true)  String role,
			HttpServletRequest request,      HttpServletResponse response){
		 	
		logger.info("generateAuditIRReportCRV3 .. "+legalEntityCode + " :: "+ auditId );
		if((legalEntityCode>=0) && (auditId!=null && !BankAuditUtil.isEmptyString(auditId)) ){ 
			try { 				
 
				String logoPath =  request.getServletContext().getRealPath("/assets/ir_logo.png"); 
			    Map<String, Object> params = new HashMap<String, Object>();					
			    params.put("logo", logoPath); 
			    String uploadPath = auditBookReportServiceV3.generatePDFReportSR(params, legalEntityCode, auditId, auditTypeCode, userId, 
			    		false, "", "", "", reportLanguage, actionType, role);
					
				if(uploadPath!=null){
			    	 File file=new File(uploadPath);
			    	 FileInputStream inputStream = new FileInputStream(file); 		    	    
					 String mimeType ="application/pdf";  						 
		             response.setContentType(mimeType); 
		             String headerKey = "Content-Disposition";
		             String headerValue = String.format("attachment; filename=\"%s\"",file.getName());
		             response.setHeader(headerKey, headerValue); 
		             OutputStream outStream = response.getOutputStream();
		            
		             byte[] buffer = new byte[4096*4096]; // 4096-> bufferSize
		             int bytesRead = -1;
		       
		             while ((bytesRead = inputStream.read(buffer)) != -1) {
		                 outStream.write(buffer, 0, bytesRead);
		             }
		             inputStream.close();
		             outStream.close();                
		    	}else {
					 response.getWriter().print("Document not exist");
				}			     
			} catch (Exception e) {
				e.printStackTrace();					
			}
		}		 
	} 
	
	
@RequestMapping(value = "/generateAuditSRReportFinal", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus  generateAuditSRReportFinal(
			@RequestParam("legalEntityCode") int legalEntityCode,
			@RequestParam(value="auditId",required=true) String auditId,
		 	@RequestParam(value="auditTypeCode",required=true) String auditTypeCode,
		 	@RequestParam(value="planId",required=true) String planId, 
		 	@RequestParam(value="unitId",required=true) String unitId,  
		 	@RequestParam(value="userId",required=true) String userId,
			@RequestParam(value="reportLanguage", required=true) String reportLanguage,
			@RequestParam(value="actionType", required=true) String actionType,
			@RequestParam(value="role", required=true)  String role,
			HttpServletRequest request,      HttpServletResponse response){
		 	
		logger.info("generateAuditBookReport .. "+legalEntityCode + " :: "+ auditId );
		ServiceStatus serviceStatus=new ServiceStatus();	
		if((legalEntityCode>=0) && (auditId!=null && !BankAuditUtil.isEmptyString(auditId)) ){ 
			try { 				
 
				String logoPath =  request.getServletContext().getRealPath("/assets/ir_logo.png"); 
			    Map<String, Object> params = new HashMap<String, Object>();					
			    params.put("logo", logoPath); 
			    String status = auditBookReportServiceV3.generatePDFReportSR(params, legalEntityCode, auditId, auditTypeCode, userId, true, planId, unitId,
			    		BankAuditConstant.REPORT_CODE_SR, reportLanguage, actionType, role);
					
			    if(status.equalsIgnoreCase(BankAuditConstant.SUCCESS)){
					serviceStatus.setMessage("success");
					serviceStatus.setStatus("success");
		    	}else {
		    		serviceStatus.setMessage("Failed to finalize the Scrutiny report");
					serviceStatus.setStatus("failed");
				}			     
			} catch (Exception e) {
				e.printStackTrace();	
				serviceStatus.setMessage("failed");
				serviceStatus.setStatus("failed");
			}
		}		 
		return serviceStatus;
	}
	
	
@RequestMapping(value = "/storeToMasterTableV3", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus  storeToMasterTableV3(
			@RequestParam("legalEntityCode") int legalEntityCode,
			@RequestParam(value="auditId",required=true) String auditId,
			@RequestParam(value="auditTypeCode",required=true) String auditTypeCode,
			@RequestParam(value="reportLanguage", required=true) String reportLanguage, 
			HttpServletRequest request,      HttpServletResponse response){

		ServiceStatus serviceStatus=new ServiceStatus();		
		logger.info("generateAuditBookReport .. "+legalEntityCode + " :: "+ auditId );
		
		if((legalEntityCode>=0) && (auditId!=null && !BankAuditUtil.isEmptyString(auditId)) ){ 
			try { 				
			   String statusMessage = auditBookReportServiceV3.storeReportDataIntoReportTable(legalEntityCode, auditId, auditTypeCode, reportLanguage);
			   if(statusMessage.equalsIgnoreCase(BankAuditConstant.SUCCESS)){
				   serviceStatus.setMessage("success");
				   serviceStatus.setStatus("success");
			   }else{
				   serviceStatus.setStatus("failed");	
				   serviceStatus.setMessage("failed");	
			   }
			} catch (Exception e) {
				 serviceStatus.setStatus("failed");	
				 serviceStatus.setMessage(e.getMessage());	
			}
		}		
		return serviceStatus;
	}
	
	
@RequestMapping(value="/downloadFinalizedReportByReportCode/{legalEntityCode}/{auditId}/{auditTypeCode}/{reportCode}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	void downloadFinalizedReportByAuditIdAndReportCode(
			@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("auditId") String auditId,
			@PathVariable("auditTypeCode") String auditTypeCode,
			@PathVariable("reportCode") String reportCode, 
			HttpServletRequest request,      HttpServletResponse response) throws IOException{
		
		if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(reportCode)  && !BankAuditUtil.isEmptyString(auditId)){
			String uploadPath = auditBookReportServiceV3.getFinalizedReport(legalEntityCode, auditId, auditTypeCode, reportCode);			
			if(uploadPath!=null){
		    	 File file=new File(uploadPath);
		    	 FileInputStream inputStream = new FileInputStream(file); 		    	    
				 String mimeType ="application/pdf";  						 
	             response.setContentType(mimeType); 
	             String headerKey = "Content-Disposition";
	             String headerValue = String.format("attachment; filename=\"%s\"",file.getName());
	             response.setHeader(headerKey, headerValue); 
	             OutputStream outStream = response.getOutputStream();
	            
	             byte[] buffer = new byte[4096*4096]; // 4096-> bufferSize
	             int bytesRead = -1;
	       
	             while ((bytesRead = inputStream.read(buffer)) != -1) {
	                 outStream.write(buffer, 0, bytesRead);
	             }
	             inputStream.close();
	             outStream.close();                
	    	}else {
				 response.getWriter().print(reportCode+" Report not exist");
			}		 
		}else {
			response.getWriter().print(reportCode+" Report not exist");
		}
				 
	}
	
	
@RequestMapping(value = "/generatePDFProfile", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	void  generatePDFProfile(
			@RequestParam("legalEntityCode") int legalEntityCode,
			@RequestParam(value="auditId",required=true) String auditId,
		 	@RequestParam(value="auditTypeCode",required=true) String auditTypeCode,
		 	@RequestParam(value="userId",required=true) String userId,
			@RequestParam(value="reportLanguage", required=false) String reportLanguage, 
			HttpServletRequest request,      HttpServletResponse response){
		 	
		logger.info("generatePDFProfile .. "+legalEntityCode + " :: "+ auditId );
		if((legalEntityCode>=0) && (auditId!=null && !BankAuditUtil.isEmptyString(auditId)) ){ 
			try { 				
 
				String logoPath =  request.getServletContext().getRealPath("/assets/ir_logo.png"); 
			    Map<String, Object> params = new HashMap<String, Object>();					
			    params.put("logo", logoPath); 
			    String uploadPath = auditBookReportServiceV3.generatePDFProfile(params, legalEntityCode, auditId, auditTypeCode, userId, "", "", reportLanguage);
					
				if(uploadPath!=null){
			    	 File file=new File(uploadPath);
			    	 FileInputStream inputStream = new FileInputStream(file); 		    	    
					 String mimeType ="application/pdf";  						 
		             response.setContentType(mimeType); 
		             String headerKey = "Content-Disposition";
		             String headerValue = String.format("attachment; filename=\"%s\"",file.getName());
		             response.setHeader(headerKey, headerValue); 
		             OutputStream outStream = response.getOutputStream();
		            
		             byte[] buffer = new byte[4096*4096]; // 4096-> bufferSize
		             int bytesRead = -1;
		       
		             while ((bytesRead = inputStream.read(buffer)) != -1) {
		                 outStream.write(buffer, 0, bytesRead);
		             }
		             inputStream.close();
		             outStream.close();                
		    	}else {
					 response.getWriter().print("Document not exist");
				}			     
			} catch (Exception e) {
				e.printStackTrace();					
			}
		}		 
	}
	
	
@RequestMapping(value = "/generateOutStandingReport", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public void  generateOutStandingReport(
			@RequestParam("legalEntityCode") int legalEntityCode,
			@RequestParam(value="auditId",required=true) String auditId,
		 	@RequestParam(value="auditTypeCode",required=true) String auditTypeCode,
		 	@RequestParam(value="planId",required=true) String planId, 
		 	@RequestParam(value="unitId",required=true) String unitId,  
		 	@RequestParam(value="userId",required=true) String userId,
			@RequestParam(value="reportLanguage", required=true) String reportLanguage, 
			@RequestParam(value="role", required=true)  String role,
			HttpServletRequest request,      HttpServletResponse response){
		 	
		logger.info("generateOutStandingReport .. "+legalEntityCode + " :: "+ auditId );
		if((legalEntityCode>=0) && (auditId!=null && !BankAuditUtil.isEmptyString(auditId)) ){ 
			try { 	
				String logoPath =  request.getServletContext().getRealPath("/assets/ir_logo.png"); 
			    Map<String, Object> params = new HashMap<String, Object>();					
			    params.put("logo", logoPath); 
			    String uploadPath = auditBookReportServiceV3.generateOutStandingReport(params, legalEntityCode, auditId, auditTypeCode, userId, 
			    		false, planId, unitId, "Out_Standing", reportLanguage, role);  		
					
				if(uploadPath!=null){
			    	 File file=new File(uploadPath);
			    	 FileInputStream inputStream = new FileInputStream(file); 		    	    
					 String mimeType ="application/pdf";  						 
		             response.setContentType(mimeType); 
		             String headerKey = "Content-Disposition";
		             String headerValue = String.format("attachment; filename=\"%s\"",file.getName());
		             response.setHeader(headerKey, headerValue); 
		             OutputStream outStream = response.getOutputStream();
		            
		             byte[] buffer = new byte[4096*4096]; // 4096-> bufferSize
		             int bytesRead = -1;
		       
		             while ((bytesRead = inputStream.read(buffer)) != -1) {
		                 outStream.write(buffer, 0, bytesRead);
		             }
		             inputStream.close();
		             outStream.close();                
		    	}else {
					 response.getWriter().print("Document not exist");
				}			     
			} catch (Exception e) {
				e.printStackTrace();					
			}
		}		 
	} 
 }
