/*!
 * SAPUI5
 * (c) Copyright 2026 SAP SE. All rights reserved.
 */

// --------------------------------------------------------------------------------
// Utility class to provide DateRangeType related functions
// --------------------------------------------------------------------------------
sap.ui.define(["sap/ui/comp/config/condition/DateRangeType"], function (DateRangeType) {
	"use strict";
	function formatCalendarDate(vValue, oModelType) {
		if (vValue instanceof Date && oModelType?.parseValue) {
			return oModelType.parseValue(vValue, "date");
		}
		return vValue;
	}

	/**
	 * Utility class to provide DateRangeType related functions
	 *
	 * @private
	 */
	var DateRangeTypeUtils = {
		_calculateDateRangeValues: function ({ columnKey, dateFormatSettings, conditionTypeInfo, fieldViewMetadata }) {
			const oFieldViewMetadata = Object.assign({}, fieldViewMetadata, { ui5Type: fieldViewMetadata.modelType });

			if (!conditionTypeInfo?.operation) {
				return null;
			}

			const oFakeFilterProvider = {
					_oDateFormatSettings: dateFormatSettings || { UTC: true },
					_getType: () => { return oFieldViewMetadata.ui5Type; },
					_createFilterControlId: () => { return "fakeFilterControlId"; }
				},
				oDateRangeType = new DateRangeType(columnKey, oFakeFilterProvider, oFieldViewMetadata);

			oDateRangeType.getControls = () => {};
			oDateRangeType.initialize({ items: [], value: null });
			oDateRangeType.setCondition(conditionTypeInfo);

			const oOperation = oDateRangeType.getOperation(conditionTypeInfo.operation),
				  aRanges = oDateRangeType.getFilterRanges();

			let oResult = null;

			if (aRanges?.length > 0) {
				oResult = {
					oValue1: aRanges[0].value1,
					oValue2: aRanges[0].value2
				};
			} else if (oOperation?.category?.startsWith("FIXED.")) {
				const aDefaultValues = oDateRangeType.getDefaultValues(oOperation);
				if (aDefaultValues?.length > 0) {
					const bSingleFilter = fieldViewMetadata?.filterRestriction === "single-value";
					const bIsCalendarDate = fieldViewMetadata?.isCalendarDate;
					const oModelType = fieldViewMetadata?.modelType;

					let oValue1 = aDefaultValues[0]?.oDate || aDefaultValues[0];
					let oValue2 = bSingleFilter ? undefined : (aDefaultValues[1]?.oDate || aDefaultValues[1]);

					if (bIsCalendarDate) {
						oValue1 = formatCalendarDate(oValue1, oModelType);
						oValue2 = formatCalendarDate(oValue2, oModelType);
					}

					oResult = {
						oValue1: oValue1,
						oValue2: oValue2
					};
				}
			}

			oDateRangeType?.destroy?.();
			return oResult;
		}
	};

	return DateRangeTypeUtils;
});
