package com.bankaudit.rest.process.controller;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.util.List;

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.RequestBody;
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 org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.bankaudit.constants.BankAuditConstant;
import com.bankaudit.dto.process.AuditRatingComplianceObsScoreReportDto;
import com.bankaudit.dto.process.AuditRatingComplianceScoreDto;
import com.bankaudit.process.model.AuditLevelDocumentDetails;
import com.bankaudit.process.model.AuditRatingComplianceObsScore;
import com.bankaudit.rest.process.service.AuditRatingComplianceScoreService;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;



@RestController

@RequestMapping("/api/auditRatingComplianceScore")
public class AuditRatingComplianceScoreController {
	@Autowired
	AuditRatingComplianceScoreService auditRatingComplianceScoreService;
	
	@Autowired
	BusinessDateService businessDateService;
	
	static final Logger logger = Logger.getLogger(AuditRatingComplianceScoreController.class);	
	
	
@RequestMapping(value="/insertAuditComplianceObsScore/{legalEntityCode}/{auditId}/{unitId}/{auditTypeCode}/{userId}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus insertAuditComplianceObsScore(
			@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("auditId")String auditId,
			@PathVariable("unitId")String unitId,
			@PathVariable("auditTypeCode")String auditTypeCode,
			@PathVariable("userId")String userId){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(auditId) && !BankAuditUtil.isEmptyString(unitId) && !BankAuditUtil.isEmptyString(auditTypeCode)){
			try {
				List<AuditRatingComplianceObsScore> auditParamScrLst=auditRatingComplianceScoreService.insertAuditComplianceObsScore(legalEntityCode,auditId,unitId,auditTypeCode,userId); 
				if(auditParamScrLst!=null){
					serviceStatus.setResult(auditParamScrLst);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("Insertion failure");
				}				
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid parameter");
		}
		return serviceStatus;
	}
	
	
@RequestMapping(value="/getComplianceObsScoreByAuditId/{legalEntityCode}/{auditId}/{auditTypeCode}/{unitId}/{userType}/{userId}/{compRatingStatus}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getComplianceObsScoreByAuditId(
			@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("auditTypeCode") String auditTypeCode,
			@PathVariable("auditId")String auditId,
			@PathVariable("unitId")String unitId,
			@PathVariable("userType")String userType,
			@PathVariable("userId")String userId,
			@PathVariable("compRatingStatus")String compRatingStatus){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(auditId)){
			try {
				List<AuditRatingComplianceObsScore> auditCompObsLst=auditRatingComplianceScoreService.getComplianceObsScoreByAuditId(legalEntityCode,auditId,auditTypeCode,unitId, userType,userId,compRatingStatus); 
				
				if(auditCompObsLst!=null){
					serviceStatus.setResult(auditCompObsLst);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("ids not found");
				}
				
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid parameter");
		}
				return serviceStatus;
	}
	
	
@RequestMapping(value="/updateAuditComplianceObsScores/{legalEntityCode}/{auditId}/{userType}",method=RequestMethod.PUT,produces=MediaType.APPLICATION_JSON_VALUE,consumes=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus updateAuditComplianceObsScores(@RequestBody List<AuditRatingComplianceObsScore> auditRatingComplianceObsScores,
			@PathVariable Integer legalEntityCode, @PathVariable String auditId, @PathVariable String userType){
		ServiceStatus serviceStatus = new ServiceStatus();
		logger.info("Inside updateAuditParamScores .... ");
		try{
				if(auditRatingComplianceObsScores!=null && auditRatingComplianceObsScores.size()>0){
					auditRatingComplianceScoreService.updateAuditComplianceObsScores(auditRatingComplianceObsScores, legalEntityCode, auditId, userType); 
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully created");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("No data tobe save...");
				}
			//}			
		}catch (Exception e) {
			e.printStackTrace();
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("failure"+e.getMessage());
			if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
				serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
			}
		}
		return serviceStatus;
	}
	
	
	
@RequestMapping(value="/getAuditRatingComplObsScore/{legalEntityCode}/{auditId}/{ratingType}/{userType}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getAuditRatingComplianceScores(
			@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("auditId")String auditId,
			@PathVariable("ratingType") String ratingType,
			@PathVariable("userType") String userType){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(auditId)){
			try {
				AuditRatingComplianceScoreDto auditRatingCompScores=auditRatingComplianceScoreService.getAuditRatingComplianceScores(legalEntityCode,auditId,ratingType,userType); 
				if(auditRatingCompScores!=null){
					serviceStatus.setResult(auditRatingCompScores);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("ids not found");
				}				
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid parameter");
		}
		return serviceStatus;
	}
	
	
@RequestMapping(value="/getComplianceObsScoreReportByAuditId/{legalEntityCode}/{auditId}/{userType}/{compRatingStatus}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getComplianceObsScoreReportByAuditId(
			@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("auditId")String auditId,
			@PathVariable("userType")String userType,
			@PathVariable("compRatingStatus")String compRatingStatus){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(auditId)){
			try {
				List<AuditRatingComplianceObsScore> auditCompObsLst=auditRatingComplianceScoreService.getComplianceObsScoreReportByAuditId(legalEntityCode,auditId,userType,compRatingStatus); 
				
				if(auditCompObsLst!=null){
					serviceStatus.setResult(auditCompObsLst);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("ids not found");
				}
				
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid parameter");
		}
				return serviceStatus;
	}
	
	// Report for individual Rating based on Desk or Field
	
@RequestMapping(value="/getComplianceObsScoreReportByAuditIdAndRatingType/{legalEntityCode}/{auditId}/{ratingType}/{userType}/{compRatingStatus}/{recordsWithNA}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getComplianceObsScoreReportByAuditIdAndRatingType(
			@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("auditId")String auditId,
			@PathVariable("ratingType") String ratingType,
			@PathVariable("userType")String userType,
			@PathVariable("compRatingStatus")String compRatingStatus,
			@PathVariable(value="recordsWithNA",required=false)  String recordsNA){ // recordsWithNA=Y -> scores with NA  && recordsWithNA=N -> scores with out NA 
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(auditId)){
			try {
				AuditRatingComplianceObsScoreReportDto auditCompObsDto=auditRatingComplianceScoreService.getComplianceObsScoreReportByAuditIdAndRatingType(legalEntityCode,auditId,ratingType, userType,compRatingStatus, recordsNA); 
				
				if(auditCompObsDto!=null){
					serviceStatus.setResult(auditCompObsDto);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfuly retrieved ");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("ids not found");
				}
				
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid parameter");
		}
		return serviceStatus;
	}
	
	
@RequestMapping(value = "/downloadAuditRatingComplianceObsScore", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	void downloadAuditRatingComplianceObsScore(
			@RequestParam("legalEntityCode")Integer legalEntityCode,
			@RequestParam("auditId")String auditId, 
			@RequestParam("auditTypeCode")String auditTypeCode, 
			@RequestParam(value="role")String role,  
			@RequestParam(value="ratingComplianceStatus") String ratingComplianceStatus,
			HttpServletRequest request,     
			HttpServletResponse response){
			
		try { 
			if(legalEntityCode!=null &&  !BankAuditUtil.isEmptyString(auditId) ){ 	
				ByteArrayOutputStream byteData = auditRatingComplianceScoreService.downloadAuditRatingComplianceObsScore(legalEntityCode, auditTypeCode, auditId, role, ratingComplianceStatus);
				if(byteData!=null){ 	
					 String fileName = "ComplianceRating"+"_"+auditId+"_"+legalEntityCode+".xlsx"; 	 					
					 String mimeType ="application/vnd.ms-excel";  						 
		             response.setContentType(mimeType); 
		             String headerKey = "Content-Disposition";
		             String headerValue = String.format("attachment; filename=\"%s\"", fileName);
		             response.setHeader(headerKey, headerValue); 
		             OutputStream outStream = response.getOutputStream();
		             outStream.write(byteData.toByteArray());		    
		             outStream.close();               
		    	}else {
					 response.getWriter().print("Document not exist");
		    	}     
			}else{
				response.getWriter().print("Document not exist");
			}
		}catch (Exception e) {
			e.printStackTrace();					
		}		
	}
	 
}
