package com.bankaudit.rest.process.controller;

import java.sql.Timestamp;

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 com.bankaudit.constants.BankAuditConstant;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.model.MaintAuditProcess;
import com.bankaudit.process.model.TaskDetails;
import com.bankaudit.rest.process.service.TaskDetailsService;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;



@RestController

@RequestMapping("/api/taskDetails")
public class TaskDetailsController {
	
	@Autowired
	TaskDetailsService taskDetailsService;
	
	@Autowired
	BusinessDateService businessDateService;
	
	static final Logger logger = Logger.getLogger(MyAuditsController.class);	
	
	
@RequestMapping(value = "/getAssessmentsWithAdviceClosure", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	DataTableResponse getAssessmentsWithAdviceClosure(
			@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="role")String role){

		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 = taskDetailsService.getAssessmentsWithAdviceClosure(Integer.parseInt(legalEntityCodeStr),userId,search, orderColumn, orderDirection, page, size, role);
				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 = "/getTaskListAssessmentWise", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	DataTableResponse getTaskListAssessmentWise(
			@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("planId")String planId,
			@RequestParam("auditId")String auditId,
			@RequestParam("userId")String userId){

		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 = taskDetailsService.getTaskListAssessmentWise(Integer.parseInt(legalEntityCodeStr),planId, auditId,userId,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(method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus updateTaskDetails(@RequestBody TaskDetails taskDetails){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(taskDetails!=null
				&& taskDetails.getLegalEntityCode()!=null
				&& !BankAuditUtil.isEmptyString(taskDetails.getTaskStatus())
				&& !BankAuditUtil.isEmptyString(taskDetails.getMaker())
				){
			
			try {
				
				taskDetails.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(taskDetails.getLegalEntityCode()));
				taskDetails.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				if(taskDetails.getStatus().equals(BankAuditConstant.STATUS_AUTH)){
					taskDetails.setCheckerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(taskDetails.getLegalEntityCode()));
				} else{
					taskDetails.setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(taskDetails.getLegalEntityCode()));
				}
				taskDetailsService.updateTaskDetails(taskDetails);
			    
			    serviceStatus.setStatus("success");
			    serviceStatus.setMessage("successfully updated");
		
			} catch (Exception e) {
				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 = "/deleteUnauthRejTaskDetails",method=RequestMethod.PUT,consumes=MediaType.APPLICATION_JSON_VALUE,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus deleteUnauthRejTaskDetails(@RequestBody TaskDetails taskDetails){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		if(taskDetails!=null
				&& taskDetails.getLegalEntityCode()!=null
				&& !BankAuditUtil.isEmptyString(taskDetails.getTaskStatus())
				&& !BankAuditUtil.isEmptyString(taskDetails.getMaker())
				){
			logger.info("Inside deleteUnauthRejTaskDetails .."+ taskDetails.getId() + " Statu :: "+ taskDetails.getStatus());
			try {
				
				taskDetails.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(taskDetails.getLegalEntityCode()));
				taskDetails.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				if(taskDetails.getStatus().equals(BankAuditConstant.STATUS_AUTH)){
					taskDetails.setCheckerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(taskDetails.getLegalEntityCode()));
				} else{
					taskDetails.setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(taskDetails.getLegalEntityCode()));
				}
				taskDetailsService.deleteUnauthRejTaskDetails(taskDetails);
			    
			    serviceStatus.setStatus("success");
			    serviceStatus.setMessage("successfully updated");
		
			} catch (Exception e) {
				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="/getTaskById/{legalEntityCode}/{auditId}/{observationId}/{id}/{status}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getTaskById(@PathVariable("legalEntityCode")Integer legalEntityCode,
			@PathVariable("auditId") String auditId,
			@PathVariable("observationId") String observationId,
			@PathVariable("id") String id,
			@PathVariable("status") String status
			){
		ServiceStatus serviceStatus=new ServiceStatus();
		
		logger.info("getTaskById .. "+legalEntityCode +" auditId.."+auditId + " observationId .."+ observationId +"id.. "+ id + " status.. "+status);
		if(legalEntityCode!=null && !BankAuditUtil.isEmptyString(auditId) 
				&& !BankAuditUtil.isEmptyString(observationId) && !BankAuditUtil.isEmptyString(status)){
			
			try {
			    TaskDetails taskDetails=taskDetailsService.getTaskById(legalEntityCode,id,auditId,observationId,status);
			    if(taskDetails!=null){
			    	serviceStatus.setResult(taskDetails);
				    serviceStatus.setStatus("success");
				    serviceStatus.setMessage("successfully retrieved ");	
			    }else {
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage("maintAuditProcess not found");
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("failure");
			}
			
		}else {
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("invalid payload ");
		}
		
		return serviceStatus;
	}

}
