/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2022 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jboss.installer.validators;


import org.jboss.installer.core.LanguageUtils;
import org.jboss.installer.core.ValidationResult;

public class IntRangeValidator {

    public static final String INVALID_INT_VALUE = "security_domain_screen.jdbc.invalid_int_value_error";
    public static final String INVALID_MIN_VALUE = "security_domain_screen.jdbc.invalid_min_value_error";
    public static final String INVALID_MAX_VALUE = "security_domain_screen.jdbc.invalid_max_value_error";

    private final LanguageUtils langUtils;
    private final int min;
    private final int max;

    public IntRangeValidator(LanguageUtils langUtils, final int min) {
        this.langUtils = langUtils;
        this.min = min;
        this.max = Integer.MAX_VALUE;
    }

    public IntRangeValidator(LanguageUtils langUtils, final int min, final int max) {
        this.langUtils = langUtils;
        this.min = min;
        this.max = max;
    }

    public ValidationResult validate(String value) {
        int intValue;
        try {
            intValue = Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return ValidationResult.error(langUtils.getString(INVALID_INT_VALUE, value));
        }
        if (intValue < min) {
            return ValidationResult.error(langUtils.getString(INVALID_MIN_VALUE, value, Integer.toString(min)));
        }
        if (intValue > max) {
            return ValidationResult.error(langUtils.getString(INVALID_MAX_VALUE, value, Integer.toString(max)));
        }
        return ValidationResult.ok();
    }
}
