import { addMinutes, differenceInMinutes, roundToNearestMinutes } from 'date-fns';

export const SNAP_MINUTES = 15;
export const DEFAULT_PIXELS_PER_HOUR = 100;

/**
 * Snap a date to the nearest 15 minutes
 */
export function snapDate(date: Date): Date {
    return roundToNearestMinutes(date, { nearestTo: SNAP_MINUTES });
}

/**
 * Calculate pixel position from date relative to start time
 */
export function getPosition(date: Date, startTime: Date, pixelsPerHour: number): number {
    const diffMinutes = differenceInMinutes(date, startTime);
    const pixelsPerMinute = pixelsPerHour / 60;
    return diffMinutes * pixelsPerMinute;
}

/**
 * Calculate date from pixel position relative to start time
 */
export function getDateFromPosition(pixels: number, startTime: Date, pixelsPerHour: number): Date {
    const pixelsPerMinute = pixelsPerHour / 60;
    const minutes = pixels / pixelsPerMinute;
    return addMinutes(startTime, minutes);
}

/**
 * Snap pixel value to nearest grid line (15 min)
 */
export function snapPixels(pixels: number, pixelsPerHour: number): number {
    const pixelsPerMinute = pixelsPerHour / 60;
    const snapPixels = SNAP_MINUTES * pixelsPerMinute;
    return Math.round(pixels / snapPixels) * snapPixels;
}
