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

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

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.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.report.v2.service.AuditBookReportServiceV2;
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/auditReport")
public class ReportBookControllerV2 {

	 
	ServiceStatus serviceStatus;
	
	@Autowired
	AuditBookReportServiceV2 auditBookReportServiceV2;
	 
	static final Logger logger = Logger.getLogger(ReportBookControllerV2.class);
	
	/**
	 * This method is to fetch all branches which are fall under schedule plan start and end dates. 
	 * @param legalEntityCode
	 * @param auditTypecode
	 * @param planStartDate
	 * @param planEndDate
	 * @param maker
	 * @return 
	 * @return AuditPlansList
	 */
	
@RequestMapping(value = "/generateAuditBookReportV2", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	void  generateAuditBookReportV2(
			@RequestParam("legalEntityCode") int legalEntityCode,
			@RequestParam(value="auditId",required=true) String auditId,
			@RequestParam(value="reportLanguage", required=false) String reportLanguage, 
			HttpServletRequest request,      HttpServletResponse response){

		serviceStatus=new ServiceStatus();		
		logger.info("generateAuditBookReport .. "+legalEntityCode + " :: "+ auditId );
			if((legalEntityCode>=0) && (auditId!=null && !BankAuditUtil.isEmptyString(auditId)) ){ 
				try {
					//Boolean isReportGenerate = true;
				    Map<String, Object> params = new HashMap<String, Object>();					
				     String uploadPath = auditBookReportServiceV2.generatePDFReport(params, legalEntityCode, auditId);
				 
				     if(uploadPath!=null){
				    	 File file=new File(uploadPath);
				    	 FileInputStream inputStream = new FileInputStream(file);
				    	 
				    	 /*Path path = Paths.get(file.getAbsolutePath());
				         ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
				    	// InputStreamResource resource = new InputStreamResource(inputStream);				    	 
				    	 HttpHeaders headers = new HttpHeaders();
				         headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
				         headers.add("Pragma", "no-cache");
				         headers.add("Expires", "0");
				    	    return ResponseEntity.ok()
				    	            .headers(headers)
				    	            .contentLength(file.length())
				    	            .contentType(MediaType.APPLICATION_PDF)
				    	            .body(resource);*/
				    	    
						 String mimeType ="application/pdf";  						 
			             response.setContentType(mimeType);
			             //response.setContentLength((int) uploadPath.length()); 
			             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");
					}					  
					   /*  Map<String, Object> params = new HashMap<String, Object>();					
							byte[] bytes = auditBookReportService.generatePDFReport(params, legalEntityCode, auditId);
							return ResponseEntity.ok().header("Content-Type", "application/pdf; charset=UTF-8")
									.header("Content-Disposition", "inline; filename=\"" + "Test" + ".pdf\"").body(bytes);   
						    */ 
				} catch (Exception e) {
					e.printStackTrace();					
				}
			}		 
	}
 }
