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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
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.process.model.AuditSchedule;
import com.bankaudit.rest.process.service.AuditPlanUpdateService;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;



@RestController

@RequestMapping("/api/auditPlanUpdate")
public class AuditPlanUpdateController {

	@Autowired
	AuditPlanUpdateService auditPlanUpdateService;

	@Autowired
	BusinessDateService businessDateService;

	static final Logger logger = Logger.getLogger(AuditPlanUpdateController.class);

	
@GetMapping(value = "/getAuditPlanUpdateList", produces = MediaType.APPLICATION_JSON_VALUE)
	DataTableResponse getAuditPlanSchedules(@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;

		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 getAuditPlanUpdateList legalEntityCode:: "+legalEntityCodeStr +" userId:: "+ userId+ "financialYear:: "+ financialYear+" auditTypeCode:: "+auditTypeCode);
				dataTableResponse = auditPlanUpdateService.getAuditPlanUpdateList(Integer.parseInt(legalEntityCodeStr), userId, search, orderColumn,
						orderDirection, page, size, financialYear, auditTypeCode);
				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;
	}

	
@GetMapping(value = "/getByPlanIdAndAuditId/{legalEntityCode}/{auditTypeCode}/{planId}/{auditId}/{status}", produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getAuditByPlanIdAndAuditId(@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("auditTypeCode") String auditTypeCode, @PathVariable("planId") String planId, @PathVariable("auditId") String auditId,
			 @PathVariable("status") String status) {
		ServiceStatus serviceStatus = new ServiceStatus();
		if (legalEntityCode != null && !BankAuditUtil.isEmptyString(auditTypeCode) && !BankAuditUtil.isEmptyString(planId)
				&& !BankAuditUtil.isEmptyString(auditId)) {
			try {
				AuditSchedule auditDtl = auditPlanUpdateService.getAuditByPlanIdAndAuditId(legalEntityCode, auditTypeCode, planId, auditId,status);
				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;
	}

	

	@PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
	public ServiceStatus updateAuditPlans(@RequestBody AuditSchedule auditSchedule) {
		ServiceStatus serviceStatus = new ServiceStatus();
		if (auditSchedule != null && auditSchedule.getLegalEntityCode() != null && auditSchedule.getAuditId() != null) {
			try {
				auditSchedule
						.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditSchedule.getLegalEntityCode()));
				auditSchedule.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				if (auditSchedule.getTeamStatus().equals(BankAuditConstant.STATUS_AUTH)) {
					auditSchedule
							.setCheckerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditSchedule.getLegalEntityCode()));
				} else {
					auditSchedule
							.setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(auditSchedule.getLegalEntityCode()));
				}
				auditPlanUpdateService.updateAuditSchedule(auditSchedule);
				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;
	}

}
