class ConfigPropertyServiceImpl implements ConfigPropertyService {

	@Override
	public ConfigPropertyAuditTrail listAllConfigPropertyAudits(String timestamp) throws Exception {

		if (StringUtils.isEmpty(timestamp)) {
			LocalDateTime now = LocalDateTime.now();
			timestamp = now.minusMonths(1).format(DateTimeFormatter.ofPattern(DATE_FORMAT));
		}

		List<ConfigPropertyAudit> allStoredAudits = configPropertyAuditRepository
				.findAllByOrderByModifiedDateDescModifiedByAsc();

		Comparator<ConfigPropertyAudit> comp = ((m2, m1) -> LocalDateTime
	                .parse(m1.getModifiedDate(), DateTimeFormatter.ofPattern(DATE_FORMAT)).compareTo(
	                        LocalDateTime.parse(m2.getModifiedDate(), DateTimeFormatter.ofPattern(DATE_FORMAT))));
	    Collections.sort(allStoredAudits, comp);
		
		ConfigPropertyAuditItem previousAuditItem = new ConfigPropertyAuditItem();
		ConfigPropertyAuditItem currentAuditItem = new ConfigPropertyAuditItem();
		List<ConfigPropertyDataChange> dataChangeList = new ArrayList<ConfigPropertyDataChange>();

		List<ConfigPropertyAuditItem> auditItemList = new ArrayList<>();

		// If the timestamp as well as the modified user is the same, we assume that the
		// records are part of the same commit
		for (ConfigPropertyAudit storedAudit : allStoredAudits) {
			if (LocalDateTime.parse(storedAudit.getModifiedDate(), DateTimeFormatter.ofPattern(DATE_FORMAT))
					.isBefore(LocalDateTime.parse(timestamp, DateTimeFormatter.ofPattern(DATE_FORMAT)))) {
				break;
			}

			if (!(storedAudit.getModifiedDate().equals(previousAuditItem.getAuditTimeStamp())
					&& storedAudit.getModifiedBy().equals(previousAuditItem.getModifiedBy()))) {

				if (currentAuditItem.getAuditTimeStamp() != null) {
					auditItemList.add(currentAuditItem);
					currentAuditItem = new ConfigPropertyAuditItem();
					dataChangeList = new ArrayList<ConfigPropertyDataChange>();
				}

			}
			currentAuditItem.setConfigPropertyChangeList(dataChangeList);
			currentAuditItem.setAuditTimeStamp(storedAudit.getModifiedDate());
			currentAuditItem.setModifiedBy(storedAudit.getModifiedBy());
			currentAuditItem.setUserMessage(storedAudit.getUserMessage());
			currentAuditItem.setSystemMessage(storedAudit.getSystemMessage());

			ConfigPropertyDataChange dataChange = new ConfigPropertyDataChange();
			dataChange.setConfigKey(storedAudit.getCfkey());
			dataChange.setApplication(storedAudit.getApplication());
			dataChange.setOldConfigValue(storedAudit.getOldvalue());
			dataChange.setNewConfigValue(storedAudit.getNewvalue());
			dataChangeList.add(dataChange);
			previousAuditItem = currentAuditItem;

		}
		// The leftover item which got missed in the iteration
		if (currentAuditItem.getAuditTimeStamp() != null) {
			auditItemList.add(currentAuditItem);
		}

		ConfigPropertyAuditTrail trail = new ConfigPropertyAuditTrail();

		trail.setConfigPropertyAudit(auditItemList);

		return trail;
	}

}