"use strict";
/*
 * Copyright 2023 Palantir Technologies, Inc. All rights reserved.
 *
 * 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.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.useDateParser = void 0;
var tslib_1 = require("tslib");
var React = tslib_1.__importStar(require("react"));
var dateFnsFormatUtils_1 = require("../../common/dateFnsFormatUtils");
var dateFnsLocaleProps_1 = require("../../common/dateFnsLocaleProps");
var INVALID_DATE = new Date(undefined);
/**
 * Create a date string parser function based on a given locale.
 *
 * Prefer using user-provided `props.parseDate` and `props.dateFnsFormat` if available, otherwise fall back to
 * default formats inferred from time picker props.
 */
function useDateParser(props, locale) {
    var _a = props, dateFnsFormat = _a.dateFnsFormat, invalidDateMessage = _a.invalidDateMessage, localeFromProps = _a.locale, outOfRangeMessage = _a.outOfRangeMessage, parseDate = _a.parseDate, timePickerProps = _a.timePickerProps, timePrecision = _a.timePrecision;
    return React.useCallback(function (dateString) {
        var _a;
        if (dateString === outOfRangeMessage || dateString === invalidDateMessage) {
            return null;
        }
        var newDate = null;
        if (parseDate !== undefined) {
            // user-provided date parser
            newDate = parseDate(dateString, (_a = locale === null || locale === void 0 ? void 0 : locale.code) !== null && _a !== void 0 ? _a : (0, dateFnsLocaleProps_1.getLocaleCodeFromProps)(localeFromProps));
        }
        else {
            // use user-provided date-fns format or one of the default formats inferred from time picker props
            var format = dateFnsFormat !== null && dateFnsFormat !== void 0 ? dateFnsFormat : (0, dateFnsFormatUtils_1.getDefaultDateFnsFormat)({ timePickerProps: timePickerProps, timePrecision: timePrecision });
            newDate = (0, dateFnsFormatUtils_1.getDateFnsParser)(format, locale)(dateString);
        }
        return newDate === false ? INVALID_DATE : newDate;
    }, [
        dateFnsFormat,
        invalidDateMessage,
        locale,
        localeFromProps,
        outOfRangeMessage,
        parseDate,
        timePickerProps,
        timePrecision,
    ]);
}
exports.useDateParser = useDateParser;
//# sourceMappingURL=useDateParser.js.map