package com.bankaudit.rest.controller;

import java.sql.Timestamp;
import java.util.List;

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.UserLeavePlanner;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.SequenceAppenderService;
import com.bankaudit.service.UserLeavePlannerService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;



@RestController

@RequestMapping("/api/userLeavePlanner")
public class UserLeavePlannerController {
	
	/**
	 * The User Leave Planner service is autowired and make methods available
	 * from service layer .
	 */
	@Autowired
	UserLeavePlannerService userLeavePlannerService;
	
	/**
	 * The business date service is autowired and make methods available from
	 * service layer .
	 */
	@Autowired
	BusinessDateService businessDateService;
	
	@Autowired
	SequenceAppenderService sequenceAppenderService;
	
	static final Logger logger = Logger.getLogger(UserLeavePlannerController.class);
	
	/**
	 * This method is use to capture the User Leaves .
	 *
	 * @param userLeavePlanner
	 *            specify the user Leave Planner
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus createUserLeaves(@RequestBody UserLeavePlanner userLeavePlanner) {
		ServiceStatus serviceStatus = new ServiceStatus();

		if (userLeavePlanner != null && userLeavePlanner.getLegalEntityCode() !=null 
				&& !BankAuditUtil.isEmptyString(userLeavePlanner.getUserId())
				&& !BankAuditUtil.isEmptyString(userLeavePlanner.getLeaveType())
				&& userLeavePlanner.getStartDate() != null  && userLeavePlanner.getEndDate() != null
		) {
			try {
				logger.info("Inside UserLeaves create " + userLeavePlanner.getLegalEntityCode() +" UserId.."+userLeavePlanner.getUserId()+" LeaveType.."+userLeavePlanner.getLeaveType());
				logger.info("StartDate.." + userLeavePlanner.getStartDate() +" Enddate.."+userLeavePlanner.getEndDate());

				userLeavePlanner.setBusinessdateTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(userLeavePlanner.getLegalEntityCode()));
				userLeavePlanner.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				userLeavePlanner.setMakerTimestamp(userLeavePlanner.getBusinessdateTimestamp());
			   

				serviceStatus = userLeavePlannerService.validateUserLeaves(userLeavePlanner);
				System.out.println("serviceStatus ...." + serviceStatus);
				if (!"failure".equalsIgnoreCase(serviceStatus.getStatus())) {
					userLeavePlanner.setId(Integer.parseInt(sequenceAppenderService.getAutoSequenceId()));
					userLeavePlannerService.createUserLeave(userLeavePlanner);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully created");
				}
			} 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;
	}

	/**
	 * This method is use to Update the User Leaves.
	 *
	 * @param maintHoliday
	 *            specify the User Leave Planner
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus updateUserLeave(@RequestBody UserLeavePlanner userLeavePlanner) {
		ServiceStatus serviceStatus = new ServiceStatus();

		if (userLeavePlanner != null && userLeavePlanner.getLegalEntityCode() != null
				&& !BankAuditUtil.isEmptyString(userLeavePlanner.getUserId())
				&& !BankAuditUtil.isEmptyString(userLeavePlanner.getLeaveType())
				&& userLeavePlanner.getStartDate() != null )
		{
			try {
				logger.info("Inside User Leaves Update  " + userLeavePlanner.getLegalEntityCode() +" UserId.." +userLeavePlanner.getUserId() 
						+" LeaveType.."+ userLeavePlanner.getLeaveType()+" StartDate.."+userLeavePlanner.getStartDate());
				//userLeavePlanner.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				
				/*if(userLeavePlanner.getStatus().equals(BankAuditConstant.STATUS_AUTH)){
					userLeavePlanner.setCheckerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(userLeavePlanner.getLegalEntityCode()));
				}else{
					userLeavePlanner.setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(userLeavePlanner.getLegalEntityCode()));
				}*/
				serviceStatus = userLeavePlannerService.validateUserLeaves(userLeavePlanner);
				System.out.println("serviceStatus ...." + serviceStatus);
				if (!"failure".equalsIgnoreCase(serviceStatus.getStatus())) {
					userLeavePlannerService.updateUserLeave(userLeavePlanner);
					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 = "/get/{legalEntityCode}/{id}/{status}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getUserLeaveById(
			@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("id") Integer id,
			@PathVariable(value="status",required=false) String status){
		ServiceStatus serviceStatus = new ServiceStatus();

		try {
			UserLeavePlanner userLeavePlanner = userLeavePlannerService.getUserLeaveById(legalEntityCode, id, status);
			if (userLeavePlanner != null) {
				serviceStatus.setResult(userLeavePlanner);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("successfully retrieved ");
			} else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("MaintHoliday not found");
			}

		} catch (Exception e) {
			e.printStackTrace();
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("failure");
		}

		return serviceStatus;
	}

	/**
	 * This method is use to Gets the maint holiday.
	 *
	 * @param id
	 *            specify the id
	 * @param status
	 *            specify the status
	 * @return the service status class object with response status and payload
	 *         .
	 */
	
@RequestMapping(value = "/getByUserIdLeaveType/{legalEntityCode}/{userId}/{leaveType}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getByUserIdLeaveType(
			@PathVariable("legalEntityCode") Integer legalEntityCode,
			@PathVariable("userId") String userId,
			@PathVariable(value="leaveType",required=false ) String leaveType) {
		ServiceStatus serviceStatus = new ServiceStatus();

		try {
			List<UserLeavePlanner> userLeavePlannerLst = userLeavePlannerService.getByUserIdLeaveType(legalEntityCode, userId, leaveType);
			if (userLeavePlannerLst != null) {
				serviceStatus.setResult(userLeavePlannerLst);
				serviceStatus.setStatus("success");
				serviceStatus.setMessage("successfully retrieved ");
			} else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("MaintHoliday not found");
			}

		} catch (Exception e) {
			e.printStackTrace();
			serviceStatus.setStatus("failure");
			serviceStatus.setMessage("failure");
		}

		return serviceStatus;
	}

	/**
	 * This method is use to Gets the maint holidays.
	 *
	 * @param drawStr
	 *            specify the draw str
	 * @param length
	 *            specify the length
	 * @param start
	 *            specify the start
	 * @param search
	 *            specify the search
	 * @param orderColumnStr
	 *            specify the order column str
	 * @param orderDirection
	 *            specify the order direction
	 * @param legalEntityCodeStr
	 *            specify the legal entity code str
	 * @return the data table response class object with response status and
	 *         payload .
	 */
	
@RequestMapping(value = "/getAll", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	DataTableResponse getAllUserLeaves(@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) {

		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);
				}
				dataTableResponse = userLeavePlannerService.getAllUserLeaves(Integer.parseInt(legalEntityCodeStr),search, orderColumn, orderDirection, page,
						size);
				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;
	}
	
	// Service to delete the Records, 
		
@RequestMapping(value="/deleteUserLevaePlanByID/{legalEntityCode}/{id}/{userId}",method=RequestMethod.DELETE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus deleteUserLevaePlanByID(@PathVariable("legalEntityCode")Integer legalEntityCode,
				@PathVariable("id") Integer id, @PathVariable("userId") String userId){
		ServiceStatus serviceStatus=new ServiceStatus();			
			if(legalEntityCode !=null  && id != null){
				try {
					userLeavePlannerService.deleteUserLevaePlanByID(legalEntityCode, id, userId);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("Record deleted successfully.");
				} catch (Exception e) {
					serviceStatus.setStatus("failure");
					e.printStackTrace();
					if(e instanceof org.springframework.dao.DataIntegrityViolationException) {
						serviceStatus.setMessage("DATAINTGRTY_VIOLATION");
					}
					serviceStatus.setMessage("failure");
				}
			}else {
				serviceStatus.setStatus("failure");
				serviceStatus.setMessage("invalid payload");
			}
			return serviceStatus;
		}	
	

}
