import { revertTimezoneOffset } from '../../../Scripts/common/date-formatting';
import { fireEvent } from '@nimius/event-utility';
import { initializeIntegrations } from '../index';

/**
 * Adapts a flatpickr setup with 2 pickres for 'from' and 'to' to fire the same events
 * as toubiz datepicker on the given wrapper. This allows flatpickr setups to use the same
 * integrations (e.g. remove-element-if-date-selected) as toubiz datepicker.
 *
 * This method must be called **after** both flatpickr instances have been setup.
 *
 * @param {HTMLElement} wrapper     - Element on which the events are fired.
 * @param {HTMLInputElement} from   - `<input>` element containing the 'from' datepicker.
 * @param {HTMLInputElement} to     - `<input>` element containing the 'to' datepicker.
 */
export function flatpickrToToubizDatepickerAdapter(wrapper, from, to) {
    // Element#_flatpickr is set by flatpickr itself. Nothing we can do about that.
    // eslint-disable-next-line no-underscore-dangle
    const fromInstance = from._flatpickr;
    // eslint-disable-next-line no-underscore-dangle
    const toInstance = to._flatpickr;

    const changeListener = () => {
        const start = from.value ? revertTimezoneOffset(fromInstance.parseDate(from.value)) : null;
        const end = to.value ? revertTimezoneOffset(toInstance.parseDate(to.value)) : null;

        const formattedDateStart = start ? fromInstance.formatDate(start, fromInstance.config.dateFormat) : '';
        const formattedDateEnd = end ? toInstance.formatDate(end, toInstance.config.dateFormat) : '';

        if (start && end) {
            fireEvent(wrapper, 'toubiz-date-picker.change', {
                range: { start, end },
                formatted: {
                    start: formattedDateStart,
                    end: formattedDateEnd,
                },
            });
        }
    };

    fromInstance.config.onChange.push(changeListener);
    toInstance.config.onChange.push(changeListener);
    fromInstance.config.onOpen.push(() => fireEvent(wrapper, 'toubiz-date-picker.open'));
    toInstance.config.onClose.push(() => fireEvent(wrapper, 'toubiz-date-picker.close'));
    initializeIntegrations(wrapper);
}
