/*
 * 
 */
package com.bankaudit.rest.controller;

import java.sql.Timestamp;
import java.util.Date;
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.RestController;

import com.bankaudit.constants.BankAuditConstant;
import com.bankaudit.dto.DataTableResponse;
import com.bankaudit.model.MaintHoliday;
import com.bankaudit.service.BusinessDateService;
import com.bankaudit.service.MaintHolidayService;
import com.bankaudit.service.SequenceAppenderService;
import com.bankaudit.util.BankAuditUtil;
import com.bankaudit.util.ServiceStatus;


/**
 * The Class {@link MaintHolidayController} provides the REST services to manage
 * the {@link MaintHoliday} class objects .
 *
 * @author amit.patel
 * @version 1.0
 */

@RestController

@RequestMapping("/api/maintHoliday")
public class MaintHolidayController {

	/**
	 * The maint holiday service is autowired and make methods available from
	 * service layer .
	 */
	@Autowired
	MaintHolidayService maintHolidayService; 
	
	/**
	 * The sequence appender service is autowired and make methods available
	 * from service layer .
	 */
	@Autowired
	SequenceAppenderService sequenceAppenderService;

	/**
	 * The business date service is autowired and make methods available from
	 * service layer .
	 */
	@Autowired
	BusinessDateService businessDateService;

	/** The Constant logger is used to specify the . */
	static final Logger logger = Logger.getLogger(MaintHolidayController.class);

	/**
	 * This method is use to Creates the maint holiday.
	 *
	 * @param maintHoliday
	 *            specify the maint holiday
	 * @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 createMaintHoliday(@RequestBody MaintHoliday maintHoliday) {
		ServiceStatus serviceStatus = new ServiceStatus();

		if (maintHoliday != null && !BankAuditUtil.isEmptyString(maintHoliday.getHolidayType())
				&& !BankAuditUtil.isEmptyString(maintHoliday.getDescription())
				&& !BankAuditUtil.isEmptyString(maintHoliday.getCountryAlpha3Code())
		) {
			try {
				System.out.println("Inside holiday create " + maintHoliday.getHolidayDate());

				if (BankAuditUtil.isEmptyString(maintHoliday.getMaker())) {
					maintHoliday.setMaker("SYSTEM");
				}

				if (maintHoliday.getLegalEntityCode() != null) {
					maintHoliday.setBusinessdateTimestamp(businessDateService
							.getBusinessDateTimestampByLegalEntityCode(maintHoliday.getLegalEntityCode()));
				} else {
					maintHoliday.setBusinessdateTimestamp(new Timestamp(System.currentTimeMillis()));
				}

				maintHoliday.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				maintHoliday.setMakerTimestamp(maintHoliday.getBusinessdateTimestamp());

				serviceStatus = maintHolidayService.validateHoliday(maintHoliday);
				System.out.println("serviceStatus ...." + serviceStatus);
				if (!"failure".equalsIgnoreCase(serviceStatus.getStatus())) {
					maintHoliday.setId(Integer.parseInt(sequenceAppenderService.getAutoSequenceId()));
					maintHolidayService.createMaintHoliday(maintHoliday);
					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 maint holiday.
	 *
	 * @param maintHoliday
	 *            specify the maint holiday
	 * @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 updateMaintHoliday(@RequestBody MaintHoliday maintHoliday) {
		ServiceStatus serviceStatus = new ServiceStatus();

		if (maintHoliday != null && !BankAuditUtil.isEmptyString(maintHoliday.getHolidayType())
				&& !BankAuditUtil.isEmptyString(maintHoliday.getDescription())
				&& !BankAuditUtil.isEmptyString(maintHoliday.getCountryAlpha3Code())

		) {
			try {
				System.out.println("Inside holiday update " + maintHoliday.getHolidayDate());
				if (BankAuditUtil.isEmptyString(maintHoliday.getMaker())) {
					maintHoliday.setMaker("SYSTEM");
				}

				if (maintHoliday.getLegalEntityCode() != null) {
					maintHoliday.setBusinessdateTimestamp(businessDateService
							.getBusinessDateTimestampByLegalEntityCode(maintHoliday.getLegalEntityCode()));
				} else {
					maintHoliday.setBusinessdateTimestamp(new Timestamp(System.currentTimeMillis()));
				}
				maintHoliday.setSysdateTimestamp(new Timestamp(System.currentTimeMillis()));
				if(maintHoliday.getStatus().equals(BankAuditConstant.STATUS_AUTH)){
					maintHoliday.setCheckerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintHoliday.getLegalEntityCode()));
				}else{
					maintHoliday.setMakerTimestamp(businessDateService.getBusinessDateTimestampByLegalEntityCode(maintHoliday.getLegalEntityCode()));
				}
				serviceStatus = maintHolidayService.validateHoliday(maintHoliday);
				if(!"failure".equalsIgnoreCase(serviceStatus.getStatus())){
					maintHolidayService.updateMaintHoliday(maintHoliday);
					serviceStatus.setStatus("success");
					serviceStatus.setMessage("successfully updated");
				}else{
					serviceStatus.setStatus("failure");
					serviceStatus.setMessage(serviceStatus.getMessage());
				}
			} 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 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 = "/get/{id}/{status}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	ServiceStatus getMaintHoliday(
			@PathVariable("id") Integer id,
			@PathVariable("status") String status) {
		ServiceStatus serviceStatus = new ServiceStatus();

		try {
			MaintHoliday maintHolidays = maintHolidayService.getMaintHoliday(id,status);
			if (maintHolidays != null) {
				serviceStatus.setResult(maintHolidays);
				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 getMaintHolidays(@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 = maintHolidayService.getMaintHolidays(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;
	}

	/*
	 * 
@RequestMapping(value = "/validate", method = RequestMethod.GET, produces
	 * = MediaType.APPLICATION_JSON_VALUE) ServiceStatus
	 * validateHoliday(@RequestParam("legalEntityCode") String
	 * legalEntityCode,@RequestParam("holidayType") String holidayType,
	 * 
	 * @RequestParam("countryAlpha3Code") String countryAlpha3Code,
	 * 
	 * @RequestParam("holidayDate") String holidayDate,
	 * 
	 * @RequestParam("description") String description,
	 * 
	 * @RequestParam("weekday") String weekday,
	 * 
	 * @RequestParam("modeOperation") String modeOperation){ ServiceStatus
	 * serviceStatus = new ServiceStatus();
	 * 
	 * try { MaintHoliday maintHolidays =
	 * maintHolidayService.getMaintHoliday(id); if (maintHolidays != null ) {
	 * serviceStatus.setResult(maintHolidays);
	 * 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; }
	 */
	
	// Service to delete the Records, 
		
@RequestMapping(value="/deleteHolidayByID/{legalEntityCode}/{id}/{userId}",method=RequestMethod.DELETE,produces=MediaType.APPLICATION_JSON_VALUE)
		ServiceStatus deleteHolidayByID(@PathVariable("legalEntityCode")Integer legalEntityCode,
				@PathVariable("id") Integer id, @PathVariable("userId") String userId){
		ServiceStatus serviceStatus=new ServiceStatus();			
			if(legalEntityCode !=null  && id != null){
				try {
					maintHolidayService.deleteHolidayByID(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;
		}	

}
