"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
function _export(target, all) {
    for(var name in all)Object.defineProperty(target, name, {
        enumerable: true,
        get: Object.getOwnPropertyDescriptor(all, name).get
    });
}
_export(exports, {
    get VALIDATOR_TYPE () {
        return VALIDATOR_TYPE;
    },
    get correctFormat () {
        return correctFormat;
    },
    get dateValidator () {
        return dateValidator;
    }
});
const _moment = /*#__PURE__*/ _interop_require_default(require("moment"));
const _registry = require("../../editors/registry");
const _dateEditor = require("../../editors/dateEditor");
const _dateTime = require("../../helpers/dateTime");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const VALIDATOR_TYPE = 'date';
function dateValidator(value, callback) {
    const dateEditor = (0, _registry.getEditorInstance)(_dateEditor.EDITOR_TYPE, this.instance);
    let valueToValidate = value;
    let valid = true;
    if (valueToValidate === null || valueToValidate === undefined) {
        valueToValidate = '';
    }
    let isValidFormat = (0, _moment.default)(valueToValidate, this.dateFormat || dateEditor.defaultDateFormat, true).isValid();
    let isValidDate = (0, _moment.default)(new Date(valueToValidate)).isValid() || isValidFormat;
    if (this.allowEmpty && valueToValidate === '') {
        isValidDate = true;
        isValidFormat = true;
    }
    if (!isValidDate) {
        valid = false;
    }
    if (!isValidDate && isValidFormat) {
        valid = true;
    }
    if (isValidDate && !isValidFormat) {
        if (this.correctFormat === true) {
            const correctedValue = correctFormat(valueToValidate, this.dateFormat);
            this.instance.setDataAtCell(this.visualRow, this.visualCol, correctedValue, 'dateValidator');
            valid = true;
        } else {
            valid = false;
        }
    }
    callback(valid);
}
dateValidator.VALIDATOR_TYPE = VALIDATOR_TYPE;
function correctFormat(value, dateFormat) {
    const dateFromDate = (0, _moment.default)((0, _dateTime.getNormalizedDate)(value));
    const dateFromMoment = (0, _moment.default)(value, dateFormat);
    const isAlphanumeric = value.search(/[A-Za-z]/g) > -1;
    let date;
    if (dateFromDate.isValid() && dateFromDate.format('x') === dateFromMoment.format('x') || !dateFromMoment.isValid() || isAlphanumeric) {
        date = dateFromDate;
    } else {
        date = dateFromMoment;
    }
    return date.format(dateFormat);
}
