package com.epam.ta.reportportal.core.project.validator.attribute;

import com.epam.ta.reportportal.commons.validation.BusinessRule;
import com.epam.ta.reportportal.commons.validation.Suppliers;
import com.epam.ta.reportportal.entity.enums.ProjectAttributeEnum;
import com.epam.ta.reportportal.exception.ReportPortalException;

import java.util.List;
import java.util.Map;

import static com.epam.ta.reportportal.commons.Predicates.equalTo;
import static com.epam.ta.reportportal.ws.model.ErrorType.BAD_REQUEST_ERROR;
import static java.util.Optional.ofNullable;

public class DelayBoundValidator {

	private final List<DelayBoundLessRule> rules;

	public DelayBoundValidator(List<DelayBoundLessRule> rules) {
		this.rules = rules;
	}

	public void validate(Map<String, String> currentAttributes, Map<ProjectAttributeEnum, Long> newAttributes) {
		rules.forEach(rule -> {
			final Long lowerDelay = ofNullable(newAttributes.get(rule.getLower())).orElseGet(() -> getCurrentDelay(currentAttributes,
					rule.getLower()
			));
			final Long higherDelay = ofNullable(newAttributes.get(rule.getHigher())).orElseGet(() -> getCurrentDelay(currentAttributes,
					rule.getHigher()
			));
			BusinessRule.expect(lowerDelay <= higherDelay, equalTo(Boolean.TRUE))
					.verify(BAD_REQUEST_ERROR,
							Suppliers.formattedSupplier("Delay of '{}' should not be higher than '{}'",
									rule.getLower().getAttribute(),
									rule.getHigher().getAttribute()
							).toString()
					);
		});
	}

	private Long getCurrentDelay(Map<String, String> currentAttributes, ProjectAttributeEnum attribute) {
		return ofNullable(currentAttributes.get(attribute.getAttribute())).map(this::resolveDelay)
				.orElseThrow(() -> new ReportPortalException(BAD_REQUEST_ERROR,
						Suppliers.formattedSupplier("Attribute - {} was not found"),
						attribute.getAttribute()
				));
	}

	private Long resolveDelay(String value) {
		try {
			return Long.parseLong(value);
		} catch (NumberFormatException exc) {
			throw new ReportPortalException(BAD_REQUEST_ERROR, exc.getMessage());
		}
	}
}

@@ -864,30 +864,24 @@
 ule -%3E %7B%0A%09%09%09
-final 
 Long lowerDe
@@ -1015,22 +1015,16 @@
 %09));%0A%09%09%09
-final 
 Long hig
@@ -1162,16 +1162,199 @@
 %0A%09%09%09));%0A
+%0A%09%09%09//Replace higher delay for forever keep launches case%0A%09%09%09if (rule.getHigher() == ProjectAttributeEnum.KEEP_LAUNCHES && higherDelay == 0) %7B%0A%09%09%09%09higherDelay = Long.MAX_VALUE;%0A%09%09%09%7D%0A%0A
 %09%09%09Busin

Fix bound validator for keep launches attribute