import { isMouseMovePayload } from '../mouse/mouse-payload.util';
import {
  formatTelemetryKeyboardKeySummary,
  formatTelemetryMouseClickSummary,
  formatTelemetryMouseMoveSummary,
} from '../../shared/utils/telemetry-summary-human-text.util';
import { readNumericField } from './telemetry-event-summary.payload';
import type { TelemetrySummaryRule } from './telemetry-event-summary.types';

export const mouseClickRule: TelemetrySummaryRule = {
  id: 'mouse-click',
  match: (o) =>
    o['action'] === 'click' &&
    readNumericField(o, 'x') !== null &&
    readNumericField(o, 'y') !== null &&
    readNumericField(o, 'button') !== null,
  summarize: (o) =>
    formatTelemetryMouseClickSummary(
      readNumericField(o, 'x')!,
      readNumericField(o, 'y')!,
      readNumericField(o, 'button')!,
      o['is_down'] === true,
    ),
};

export const mouseMoveRule: TelemetrySummaryRule = {
  id: 'mouse-move',
  match: (o) => isMouseMovePayload(o),
  summarize: (o) =>
    formatTelemetryMouseMoveSummary(
      readNumericField(o, 'x')!,
      readNumericField(o, 'y')!,
      readNumericField(o, 'button'),
    ),
};

export const keyboardKeyRule: TelemetrySummaryRule = {
  id: 'keyboard-key',
  match: (o) => {
    const a = o['action'];
    if (a !== 'press' && a !== 'release') {
      return false;
    }
    return typeof o['key_name'] === 'string';
  },
  summarize: (o) =>
    formatTelemetryKeyboardKeySummary(
      o['action'] === 'press' ? 'press' : 'release',
      String(o['key_name']),
      o['modifiers'],
    ),
};
