import 'dart:async';

import '../models/websocket_event.dart';
import '../models/progress_event.dart';
import '../models/execution_event.dart';

class WebSocketEventHandler {
  static void tryCreateProgressEvent(
    WebSocketEvent event,
    StreamController<ProgressEvent> progressEventController,
    List<Function(ProgressEvent)> progressEventCallbacks,
  ) {
    if (event.data.containsKey('value') &&
        event.data.containsKey('max') &&
        event.data.containsKey('prompt_id')) {
      try {
        final progressEvent = ProgressEvent(
          value: event.data['value'] as int,
          max: event.data['max'] as int,
          promptId: event.data['prompt_id'] as String,
          node: event.data['node']?.toString(),
        );
        progressEventController.add(progressEvent);

        // Trigger all registered progress callbacks
        for (final callback in progressEventCallbacks) {
          callback(progressEvent);
        }
      } catch (e) {
        print('Error creating ProgressEvent: $e');
      }
    }
  }

  static void tryCreateExecutionEvent(
    WebSocketEvent event,
    StreamController<ExecutionEvent> executionEventController,
  ) {
    if (event.data.containsKey('prompt_id')) {
      try {
        final executionEvent = ExecutionEvent(
          promptId: event.data['prompt_id'] as String,
          timestamp: event.data['timestamp'] as int? ??
              DateTime.now().millisecondsSinceEpoch,
          node: event.data['node']?.toString(),
          extra: event.data['extra'] as Map<String, dynamic>?,
        );
        executionEventController.add(executionEvent);
      } catch (e) {
        print('Error creating ExecutionEvent: $e');
      }
    }
  }
}
