import 'dart:async';
import 'dart:isolate';

import 'package:flutter/foundation.dart';
import 'package:flutter/foundation.dart' as flutter;

class BackgroundService {
  static final BackgroundService _instance = BackgroundService._internal();
  factory BackgroundService() => _instance;
  BackgroundService._internal();

  static BackgroundService get instance => _instance;

  /// Run a heavy computation in the background using compute
  /// This is useful for JSON parsing, data processing, etc.
  Future<T> compute<T, U>(ComputeCallback<U, T> callback, U message) async {
    return await flutter.compute(callback, message);
  }

  /// Run a task in an isolate with message passing capability
  Future<T> runTaskInIsolate<T>(Future<T> Function() task) async {
    final completer = Completer<T>();

    final receivePort = ReceivePort();
    final isolate = await Isolate.spawn(
      _isolateEntry<T>,
      _IsolateData<T>(receivePort.sendPort, task),
    );

    receivePort.listen((message) {
      if (message is T) {
        completer.complete(message);
        receivePort.close();
        isolate.kill();
      } else if (message is Error) {
        completer.completeError(message);
        receivePort.close();
        isolate.kill();
      }
    });

    return completer.future;
  }
}

// Helper function to run code in isolate
void _isolateEntry<T>(_IsolateData<T> data) async {
  try {
    final result = await data.task();
    data.sendPort.send(result);
  } catch (e) {
    data.sendPort.send(Error());
  }
}

// Data class for isolate communication
class _IsolateData<T> {
  final SendPort sendPort;
  final Future<T> Function() task;

  _IsolateData(this.sendPort, this.task);
}
