var BaseValidator = require('libresignage/ui/validator/BaseValidator');

/**
* @typedef {object} NumValidatorSettings
*
* @property {number}  min The minimum value.
* @property {number}  max The maximum value.
* @property {boolean} nan Allow NaN values.
* @property {boolean} float Allow float values.
*
* @memberof module:libresignage/ui/validator
* @alias    NumValidatorSettings
*/

/**
* Class for Validating numerical inputs.
*
* @memberof module:libresignage/ui/validator
*/
class NumValidator extends BaseValidator {
	/**
	* Construct a new NumValidator object.
	*
	* @param {NumValidatorSettings} settings
	* @param {string}               msg
	* @param {boolean}              nostyle
	*
	* @see {@link module:libresignage/ui/validator.BaseValidator} Parent class.
	*/
	constructor(...args) {
		super(...args);
		this.chk_settings(['min', 'max', 'nan', 'float']);
	}

	validate(element) {
		let val = null;
		let {min, max, nan, float} = this.settings;

		if (float) {
			val = parseFloat(element.value);
		} else {
			if (element.value.indexOf('.') != -1) {
				return false;
			} else {
				val = parseInt(element.value, 10);
			}
		}

		if (isNaN(val) && !nan) {
			return false;
		} else if (isNaN(val) && nan) {
			return true;
		}

		return (min == null || val >= min) && (max == null || val <= max);
	}
}
module.exports = NumValidator;
