package com.bankaudit.rest.process.controller;

import java.time.LocalDate;
import java.util.List;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
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.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.bankaudit.constants.BankAuditConstant;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.dto.process.AuditReportDynamicTableDto;
import com.bankaudit.dto.process.AuditReportDynamicTablePredefinedDataListDto;
import com.bankaudit.process.model.AuditReportDynamicTable;
import com.bankaudit.process.model.AuditSchedule;
import com.bankaudit.rest.process.service.AuditReportDynamicTableService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;



@RestController

@RequestMapping("/api/auditReportDynamicTable")
public class AuditReportDynamicTableController {
	
	@Autowired
	AuditReportDynamicTableService auditReportDynamicTableService; 
	
	static final Logger logger = Logger.getLogger(AuditReportDynamicTableController.class);
	
	
@RequestMapping(value = "/getAllDynamicTables", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	DataTableResponse getDynamicTables(
			@RequestParam("draw") String drawStr,
			@RequestParam("length") String length,
			@RequestParam("start") String start,
			@RequestParam("search[value]") String search,
			@RequestParam("order[0][column]") String orderColumnStr,
			@RequestParam("order[0][dir]") String orderDirection,
			@RequestParam("legalEntityCode")String legalEntityCodeStr,
			@RequestParam("userId")String userId,
			@RequestParam("role")String role,
			@RequestParam(required = false, value = "financialYear") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate financialYear,
			@RequestParam(required = false, value = "auditTypeCode") String auditTypeCode){

		DataTableResponse dataTableResponse = null;

		if (!BankAuditUtil.isEmptyString(drawStr) && !BankAuditUtil.isEmptyString(length) && !BankAuditUtil.isEmptyString(start)) {
			try {
				Integer draw = Integer.parseInt(drawStr);
				Integer size = Integer.parseInt(length);
				Integer page = Integer.parseInt(start) / size;
				Integer orderColumn = null;
				if (!BankAuditUtil.isEmptyString(orderColumnStr)) {
					orderColumn = Integer.parseInt(orderColumnStr);
				}
				logger.info("Inside getAllDynamicTables legalEntityCode:: "+legalEntityCodeStr +" userId:: "+ userId + "role:: "+ role);
				dataTableResponse = auditReportDynamicTableService.getDynamicTables(Integer.parseInt(legalEntityCodeStr),userId,role, search, orderColumn, 
						orderDirection, page, size, financialYear, auditTypeCode);
				logger.info("Inside controller dataTableResponse .... "+dataTableResponse);
				dataTableResponse.setDraw(draw);

			} catch (Exception e) {
				dataTableResponse = new DataTableResponse();
				dataTableResponse.setError(e.getMessage());
				e.printStackTrace();
			}

		} else {
			dataTableResponse = new DataTableResponse();
			dataTableResponse.setError("invalid data");
		}

		return dataTableResponse;
	}
	
	
@RequestMapping(value="/getDynamicTablesByAuditId/{legalEntityCode}/{auditTypeCode}/{auditId}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getDynamicTablesByAuditId(		
			@PathVariable("legalEntityCode") Integer legalEntityCode,			
			@PathVariable("auditTypeCode") String auditTypeCode,
			@PathVariable("auditId") String auditId ){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(auditId)){
			try {
				AuditReportDynamicTableDto ardDto=auditReportDynamicTableService.getDynamicTablesByAuditId(legalEntityCode, auditTypeCode, auditId);
				
				if(ardDto!=null){
					serviceStatus.setResult(ardDto);
					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="/getDynamicTablesById/{legalEntityCode}/{auditTypeCode}/{auditId}/{id}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getDynamicTablesById(		
			@PathVariable("legalEntityCode") Integer legalEntityCode,			
			@PathVariable("auditTypeCode") String auditTypeCode,
			@PathVariable("auditId") String auditId,
			@PathVariable("id") Integer id){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null && id!=null && !BankAuditUtil.isEmptyString(auditId)){
			try {
				AuditReportDynamicTableDto ardDto=auditReportDynamicTableService.getDynamicTablesById(legalEntityCode, auditTypeCode, auditId, id);
				
				if(ardDto!=null){
					serviceStatus.setResult(ardDto);
					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="/createDynamicTables",method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus createDynamicTables(@RequestBody AuditReportDynamicTableDto auditReportDynamicDtls){
		ServiceStatus serviceStatus=new ServiceStatus();
		if(auditReportDynamicDtls!=null){
			try {
				auditReportDynamicTableService.createDynamicTables(auditReportDynamicDtls);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("successsfully saved");
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				logger.error(e.getStackTrace());
			}
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("at least one observation is required ");
		}		
		return serviceStatus; 
	}
	
	
@RequestMapping(value="/updateDynamicTables",method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus updateDynamicTables(@RequestBody AuditReportDynamicTableDto auditReportDynamicDtls){
		ServiceStatus serviceStatus=new ServiceStatus();
		if(auditReportDynamicDtls!=null){
			try {
				auditReportDynamicTableService.updateDynamicTables(auditReportDynamicDtls);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("successsfully saved");
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				logger.error(e.getStackTrace());
			}
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("at least one observation is required ");
		}		
		return serviceStatus; 
	} 
	
	
@RequestMapping(value="/updateDynamicTablesSequencing",method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus updateDynamicTablesSequencing(@RequestBody AuditReportDynamicTableDto auditReportDynamicDtls){
		ServiceStatus serviceStatus=new ServiceStatus();
		logger.info(" Inside updateDynamicTablesSequencing .."+auditReportDynamicDtls );
		if(auditReportDynamicDtls!=null && auditReportDynamicDtls.getArdTableSequenceList() !=null){
			try {
				auditReportDynamicTableService.updateDynamicTablesSequencing(auditReportDynamicDtls);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("successsfully saved");
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				logger.error(e.getStackTrace());
			}
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("at least one observation is required ");
		}
		
		return serviceStatus; 
	}
	 
	
@RequestMapping(value="/deleteDynamicTablesById/{legalEntityCode}/{auditTypeCode}/{auditId}/{id}",method=RequestMethod.DELETE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus deleteDynamicTablesById(
			@PathVariable("legalEntityCode")Integer legalEntityCode, 
			@PathVariable("auditTypeCode") String auditTypeCode,
			@PathVariable("auditId") String auditId,
			@PathVariable("id") Integer id){
		ServiceStatus serviceStatus=new ServiceStatus();
		logger.info(" Inside deleteDynamicTablesById .."+legalEntityCode +" :: " +id+" :: "+auditId );
		if(legalEntityCode!=null && id !=null && auditId !=null ){
			try {
				auditReportDynamicTableService.deleteDynamicTablesById(legalEntityCode, auditTypeCode, auditId, id);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("Table deleted successfully.");
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				logger.error(e.getStackTrace());
			}
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("at least one observation is required ");
		}
		
		return serviceStatus; 
	} 
	
	
@RequestMapping(value="/getInprogressAuditbyUserId/{legalEntityCode}/{userId}/{roleId}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getInprogressAuditbyUserId(
			@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("userId") String userId,
			@PathVariable("roleId") String roleId){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(userId) && !BankAuditUtil.isEmptyString(roleId) ){
			try {
				List<AuditSchedule> list=auditReportDynamicTableService.getInprogressAuditbyUserId(legalEntityCode,userId, roleId); 
				if(list!=null){
					serviceStatus.setResult(list);
					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="/uploadDynamicTablesSheet" ,method=RequestMethod.POST,consumes=MediaType.MULTIPART_FORM_DATA_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus  uploadDynamicTablesSheet(@RequestPart AuditReportDynamicTable ardTable,  
			@RequestPart(value="files") MultipartFile[]  files)  {		          
        
		ServiceStatus serviceStatus=new ServiceStatus();
		 
		try {
			if(files!=null){				
				String statusMessage =  auditReportDynamicTableService.uploadDynamicTablesSheet(ardTable,  files);
				if(statusMessage.equalsIgnoreCase(BankAuditConstant.SUCCESS)){						
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully uploaded");
				}else if(statusMessage.equalsIgnoreCase(BankAuditConstant.FAILED)){
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("failed to upload excel");
				}else{
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage(statusMessage);
				} 
				 
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("Invalid payload");
			}
			
		} catch (Exception e) {
			logger.error(e.getStackTrace());
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("failure");
		}
		return serviceStatus;
	}  
 	
	
@RequestMapping(value = "/getPredefinedStatementDetail", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getPredefinedStatementDetail(			 
			@RequestParam("legalEntityCode")Integer legalEntityCode,
			@RequestParam("auditTypeCode")String auditTypeCode,			
			@RequestParam("auditId")String auditId,
			@RequestParam(name="auditGroupCode", required=false)String auditGroupCode,
			@RequestParam(name="auditSubGroupCode", required=false)String auditSubGroupCode,
			@RequestParam(name="activityCode", required=false)String activityCode,
			@RequestParam(name="processCode", required=false)String processCode,
			@RequestParam("statementType")String statementType,
			@RequestParam("all")String all){

		ServiceStatus serviceStatus=new ServiceStatus();		
		List<AuditReportDynamicTablePredefinedDataListDto> listData=null;
			try { 				 
				listData = auditReportDynamicTableService.getPredefinedStatementDetail(legalEntityCode, auditTypeCode, auditId, auditGroupCode,
						auditSubGroupCode, activityCode, processCode, statementType, all);
				if(listData!=null && !listData.isEmpty()){
					serviceStatus.setResult(listData);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully got the result ");					
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("No Data found ");
				}
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("No Data found "); 
				logger.error(e.getStackTrace());
				
			}
		return serviceStatus;
	}
	
	
@RequestMapping(value = "/getSavedStatementDetail", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getSavedStatementDetail(			 
			@RequestParam("legalEntityCode")Integer legalEntityCode,
			@RequestParam("auditTypeCode")String auditTypeCode,			
			@RequestParam("auditId")String auditId,
			@RequestParam(name="auditGroupCode", required=false)String auditGroupCode,
			@RequestParam(name="auditSubGroupCode", required=false)String auditSubGroupCode,
			@RequestParam(name="activityCode", required=false)String activityCode,
			@RequestParam(name="processCode", required=false)String processCode,
			@RequestParam("statementType")String statementType,
			@RequestParam(name="statementId", required=false)String statementId){

		ServiceStatus serviceStatus=new ServiceStatus();		
		AuditReportDynamicTable auditReportDynamicTable=null;
			try { 				 
				auditReportDynamicTable = auditReportDynamicTableService.getSavedStatementDetail(legalEntityCode, auditTypeCode, auditId, auditGroupCode, auditSubGroupCode,
						activityCode, processCode, statementType, statementId);
				if(auditReportDynamicTable!=null){
					serviceStatus.setResult(auditReportDynamicTable);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully got the result ");					
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("No Data found ");
				}
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("No Data found "); 
				logger.error(e.getStackTrace());
				
			}
		return serviceStatus;
	}
	 
}
