"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseFilterInputDate = exports.parseDateValue = exports.parseToISO = exports.dateToISO = exports.isValueValidDate = exports.isValidDate = void 0;
const date_fns_1 = require("date-fns");
const FormatHelper_1 = require("./FormatHelper");
const AdaptableLogger_1 = require("../../agGrid/AdaptableLogger");
const isValidDate = (date) => {
    return date instanceof Date && !isNaN(date.getTime());
};
exports.isValidDate = isValidDate;
/**
 * Checks if the data contains a value that represents a valid date.
 *
 * @param data any kind of data
 */
const isValueValidDate = (data) => {
    if (!data || typeof data === 'boolean') {
        return false;
    }
    const date = new Date(data);
    return !isNaN(date.getTime());
};
exports.isValueValidDate = isValueValidDate;
const dateToISO = (date) => {
    return (0, FormatHelper_1.DateFormatter)(date, { Pattern: 'yyyy-MM-dd' });
};
exports.dateToISO = dateToISO;
const parseToISO = (date, dateFormat) => {
    const dateInstance = (0, exports.parseDateValue)(date, dateFormat);
    return (0, exports.isValidDate)(dateInstance) ? (0, exports.dateToISO)(dateInstance) : '';
};
exports.parseToISO = parseToISO;
const parseDateValue = (dateValue, dateFormat) => {
    if (dateValue == undefined || (typeof dateValue === 'string' && dateValue.trim() === '')) {
        return undefined;
    }
    if (dateValue instanceof Date) {
        return !isNaN(dateValue.getTime()) ? dateValue : undefined;
    }
    let dateInstance;
    if (typeof dateValue === 'number') {
        dateInstance = new Date(dateValue);
    }
    else {
        // typeof dateValue === 'string'
        if (dateFormat) {
            dateInstance = (0, date_fns_1.parse)(dateValue, dateFormat, new Date());
        }
        else {
            dateInstance = (0, date_fns_1.parseISO)(dateValue);
        }
        if (!(0, exports.isValidDate)(dateInstance)) {
            // last chance: try to use the native Date.parse(), https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
            dateInstance = new Date(Date.parse(dateValue));
        }
    }
    if (!(0, exports.isValidDate)(dateInstance)) {
        AdaptableLogger_1.AdaptableLogger.consoleWarnBase(`Invalid date value "${dateValue}" - cannot be converted to a Date instance. Please make sure you specify adaptableOptions.userInterfaceOptions.dateInputOptions.dateFormat correctly.`);
        dateInstance = undefined;
    }
    return dateInstance;
};
exports.parseDateValue = parseDateValue;
const parseFilterInputDate = (stringDate) => new Date(stringDate);
exports.parseFilterInputDate = parseFilterInputDate;
