package com.bankaudit.rest.process.controller;

import java.sql.Timestamp;
import java.time.LocalDate;

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.RestController;

import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.dto.process.AuditDto;
import com.bankaudit.process.model.AuditSchedule;
import com.bankaudit.rest.process.service.AuditRespondService;
import com.bankaudit.rest.process.service.MyAuditsService;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;



@RestController

@RequestMapping("/api/auditRespond")
public class AuditRespondController {
	@Autowired 
	AuditRespondService auditRespondService;
	ServiceStatus serviceStatus;
	
	@Autowired
	BusinessDateService businessDateService;
	
	@Autowired
	MyAuditsService myAuditsService;
	
	static final Logger logger = Logger.getLogger(AuditRespondController.class);	
	
	
@RequestMapping(value = "/getMyRespond", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	DataTableResponse getAuditSchedules(
			@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(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);
				}
				System.out.println("legalEntityCode:: "+legalEntityCodeStr +" userId:: "+ userId);
				dataTableResponse = auditRespondService.getMyRespondList(Integer.parseInt(legalEntityCodeStr),userId,search, orderColumn, orderDirection, page, size, financialYear, auditTypeCode);
				System.out.println("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="/getRespondByPlanIdAndAuditId/{legalEntityCode}/{auditTypeCode}/{planId}/{auditId}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getRespondByPlanIdAndAuditId(
			@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("auditTypeCode") String auditTypeCode,
			@PathVariable("planId") String planId,
			@PathVariable("auditId")String auditId){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(legalEntityCode!=null
				&& !BankAuditUtil.isEmptyString(auditTypeCode) && !BankAuditUtil.isEmptyString(planId) && !BankAuditUtil.isEmptyString(auditId)){
			try {
				AuditSchedule auditDtl=auditRespondService.getRespondAuditByPlanIdAndAuditId(legalEntityCode,auditTypeCode,planId,auditId); 
				
				if(auditDtl!=null){
					serviceStatus.setResult(auditDtl);
					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(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus updateMyRespondStatus(@RequestBody AuditSchedule auditSchedule) {
		ServiceStatus serviceStatus = new ServiceStatus();

		if (auditSchedule != null && auditSchedule.getLegalEntityCode() != null
				&& !BankAuditUtil.isEmptyString(auditSchedule.getAuditTypeCode())
				&& !BankAuditUtil.isEmptyString(auditSchedule.getPlanId())
				&& !BankAuditUtil.isEmptyString(auditSchedule.getAuditId())
				&& !BankAuditUtil.isEmptyString(auditSchedule.getRespondStatus())
				&& !BankAuditUtil.isEmptyString(auditSchedule.getMaker())) {
			try {
				logger.info("LegalEntCode:: "+auditSchedule.getLegalEntityCode()+" AuditType:: "+auditSchedule.getAuditTypeCode()+" PanId:: "+auditSchedule.getPlanId() +" AuditId:: "+auditSchedule.getAuditId()+ " audit Status :: "+auditSchedule.getAuditStatus());
				auditSchedule.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditSchedule.getLegalEntityCode()));
				auditSchedule.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				auditSchedule.setMakerTimestamp(auditSchedule.getBusinessdateTimestamp());
				
				
				logger.info("RespStatus .. " +auditSchedule.getRespondStatus() +" ObsSts.. "+ auditSchedule.getObservationStatus());
				if(("RS").equalsIgnoreCase(auditSchedule.getRespondStatus())) { //instead of auditStatus, compared with RespondStatus
					if("AS".equalsIgnoreCase(auditSchedule.getObservationStatus())) {
						String isRespondObsPendingBfrRespondSubmit= "N";
						
						AuditDto auditDto = new AuditDto();
						auditDto.setLegalEntityCode(auditSchedule.getLegalEntityCode());
						auditDto.setAuditId(auditSchedule.getAuditId());
						auditDto.setAuditTypeCode(auditSchedule.getAuditTypeCode());
						isRespondObsPendingBfrRespondSubmit= myAuditsService.isAuditObsPending(auditDto, "RS");
						logger.info("isRespondObsPendingBfrRespondSubmit:: "+ isRespondObsPendingBfrRespondSubmit);
						if(isRespondObsPendingBfrRespondSubmit.equals("N")) {
							logger.info("in sts N:: "+ isRespondObsPendingBfrRespondSubmit);
							auditRespondService.updateAuditRespondStatus(auditSchedule);
							serviceStatus.setStatus("success");
							serviceStatus.setMessage("successfully updated");
						}else {
							serviceStatus.setStatus("failure");
							serviceStatus.setMessage("Please approve all the Risks before submitting the Audit.");
						}
					}else {
						serviceStatus.setStatus("failure");
						serviceStatus.setMessage("Please submit the Assessment before submitting the Audit.");
					}
				}else if(("RI").equalsIgnoreCase(auditSchedule.getRespondStatus())) {
					auditRespondService.updateAuditRespondStatus(auditSchedule);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully updated");
				}
			} catch (Exception e) {

				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
					serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
				}
			}

		} else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload ");
		}

		return serviceStatus;
	}
	
	
@RequestMapping(value = "/getRespondObservations", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	DataTableResponse getRespondObservations(
			@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("auditId")String auditId,
			@RequestParam("planId")String planId,
			@RequestParam("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);
				}
				System.out.println("legalEntityCode:: "+legalEntityCodeStr +" auditId:: "+ auditId+" planId:: "+planId);
				dataTableResponse = auditRespondService.getRespondObservationList(Integer.parseInt(legalEntityCodeStr),planId,auditId,search, orderColumn, orderDirection, page, size);
				System.out.println("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="/isAuditObsPendingforSubmit",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	ServiceStatus isAuditObsPendingforSubmit(
			@RequestParam("legalEntityCode")String legalEntityCodeStr,
			@RequestParam("auditId") String auditId,
			@RequestParam("auditTypeCode") String auditTypeCode
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		if(!BankAuditUtil.isEmptyString(legalEntityCodeStr) && !BankAuditUtil.isEmptyString(auditId)  && !BankAuditUtil.isEmptyString(auditTypeCode) ){
			try {
				Integer legalEntityCode=Integer.parseInt(legalEntityCodeStr);
				String isAuditObsPendingforSubmit= "N";
				
				AuditDto auditDto = new AuditDto();
				auditDto.setLegalEntityCode(legalEntityCode);
				auditDto.setAuditId(auditId);
				auditDto.setAuditTypeCode(auditTypeCode);
				isAuditObsPendingforSubmit= myAuditsService.isAuditObsPending(auditDto, "RS");
				logger.info("isAuditObsPendingforSubmit:: "+ isAuditObsPendingforSubmit);
				if(isAuditObsPendingforSubmit.equals("N")) {
					logger.info("in sts N:: "+ isAuditObsPendingforSubmit);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("All the compliance submitted");
				}else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("All the compliance are not submitted yet.");
				}				
			} catch (Exception e) {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
				e.printStackTrace();
			}			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("legalEntityCode, auditId and auditTypeCode are required");
		}
		return serviceStatus;
	}
	
}
