import { IGridConfig } from '../core/IGridConfig';

/**
 * SwpEvent - Wrapper class for calendar event elements
 *
 * Encapsulates an HTMLElement and provides computed properties
 * for start/end times based on element position and grid config.
 *
 * Usage:
 * - eventId is read from element.dataset
 * - columnKey identifies the column uniformly
 * - Position (top, height) is read from element.style
 * - Factory method `fromElement()` calculates Date objects
 */
export class SwpEvent {
  readonly element: HTMLElement;
  readonly columnKey: string;
  private _start: Date;
  private _end: Date;

  constructor(element: HTMLElement, columnKey: string, start: Date, end: Date) {
    this.element = element;
    this.columnKey = columnKey;
    this._start = start;
    this._end = end;
  }

  /** Event ID from element.dataset.eventId */
  get eventId(): string {
    return this.element.dataset.eventId || '';
  }

  get start(): Date {
    return this._start;
  }

  get end(): Date {
    return this._end;
  }

  /** Duration in minutes */
  get durationMinutes(): number {
    return (this._end.getTime() - this._start.getTime()) / (1000 * 60);
  }

  /** Duration in milliseconds */
  get durationMs(): number {
    return this._end.getTime() - this._start.getTime();
  }

  /**
   * Factory: Create SwpEvent from element + columnKey
   * Reads top/height from element.style to calculate start/end
   * @param columnKey - Opaque column identifier (do NOT parse - use only for matching)
   * @param date - Date string (YYYY-MM-DD) for time calculations
   */
  static fromElement(
    element: HTMLElement,
    columnKey: string,
    date: string,
    gridConfig: IGridConfig
  ): SwpEvent {
    const topPixels = parseFloat(element.style.top) || 0;
    const heightPixels = parseFloat(element.style.height) || 0;

    // Calculate start from top position
    const startMinutesFromGrid = (topPixels / gridConfig.hourHeight) * 60;
    const totalMinutes = (gridConfig.dayStartHour * 60) + startMinutesFromGrid;

    const start = new Date(date);
    start.setHours(Math.floor(totalMinutes / 60), totalMinutes % 60, 0, 0);

    // Calculate end from height
    const durationMinutes = (heightPixels / gridConfig.hourHeight) * 60;
    const end = new Date(start.getTime() + durationMinutes * 60 * 1000);

    return new SwpEvent(element, columnKey, start, end);
  }
}
