import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:isolate_manager/isolate_manager.dart';
import 'package:uuid/uuid.dart';
import 'package:workmanager/workmanager.dart';

import '../Tasks/BackgroundHandler/workers.dart';
import '../Tasks/BackgroundHandler/workmanager_workers.dart';

/// Erstellt Hintergrundtasks und führt diese aus
class BackgroundTaskController {
  /// Erstellt eine neue Instanz dieser Klasse
  BackgroundTaskController() {
    if (!kIsWeb && Platform.isAndroid) {
      unawaited(Workmanager().initialize(callbackDispatcher));
      unawaited(
        Workmanager().registerPeriodicTask(
          'generate-transactions',
          'generate_transactions',
          frequency: const Duration(minutes: 30),
          initialDelay: const Duration(minutes: 1),
        ),
      );
      unawaited(
        Workmanager().registerPeriodicTask(
          'show-notifications',
          'show_notifications',
          frequency: const Duration(minutes: 120),
          initialDelay: const Duration(minutes: 5),
        ),
      );
    } else {
      unawaited(
        IsolateManager.runFunction(runTask, {
          'taskName': 'generate_transactions',
          'initialDelayMinutes': 1,
          'frequencyMinutes': 30,
        }),
      );

      if (!kIsWeb) {
        unawaited(
          IsolateManager.runFunction(runTask, {
            'taskName': 'show_notifications',
            'initialDelayMinutes': 5,
            'frequencyMinutes': 120,
          }),
        );
      }
    }
  }

  /// Führt den angegebenen Task sofort aus.
  static Future<void> run(final String taskName) async {
    if (!kIsWeb && Platform.isAndroid) {
      final String uuid = const Uuid().v4();
      unawaited(Workmanager().registerOneOffTask('$taskName-$uuid', taskName));
    } else {
      unawaited(IsolateManager.runFunction(runTask, {
        'taskName': taskName,
        'initialDelayMinutes': 0,
        'frequencyMinutes': 0,
      }));
    }
  }
}
