import 'dart:developer';

import 'package:background_fetch/background_fetch.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../app.dart';
import '../homescreen_widgets/timetable/timetableHomeWidget.dart';

class ScheduledTask {
  static final String fetchApiLastRunTimestampKey = 'fetchApiLastRunTimestamp';

  static Future<void> configure() async {
    var status = await BackgroundFetch.configure(BackgroundFetchConfig(
        minimumFetchInterval: 15,
        stopOnTerminate: false,
        enableHeadless: true,
        requiresBatteryNotLow: false,
        requiresCharging: false,
        requiresStorageNotLow: false,
        requiresDeviceIdle: false,
        requiredNetworkType: NetworkType.ANY,
        startOnBoot: true,
    ), (String taskId) async {
      log('Background fetch started with id $taskId');
      await ScheduledTask.backgroundFetch();
      BackgroundFetch.finish(taskId);
    }, (String taskId) async {
      log('Background fetch stopped because of an timeout with id $taskId');
      BackgroundFetch.finish(taskId);
    });

    log('Background Fetch-API status: $status');
  }

  // called periodically, iOS and Android
  static Future<void> backgroundFetch() async {
    var sp = await SharedPreferences.getInstance();
    var history = sp.getStringList(fetchApiLastRunTimestampKey) ?? List.empty(growable: true);
    history.add(DateTime.now().toIso8601String());
    try {
      TimetableHomeWidget.update(App.appContext.currentContext!);
    } on Exception catch(e) {
      history.add('Got Error:');
      history.add(e.toString());
      history.add('--- EXCEPTION END ---');
    }
    sp.setStringList(fetchApiLastRunTimestampKey, history.take(100).toList());
  }

  // only Android, starts when app is terminated
  @pragma('vm:entry-point')
  static Future<void> headless(HeadlessTask task) async {
    var taskId = task.taskId;
    var isTimeout = task.timeout;
    if (isTimeout) {
      log('Background fetch headless task timed-out: $taskId');
      BackgroundFetch.finish(taskId);
      return;
    }
    log('Background fetch headless event received.');
    await backgroundFetch();
    BackgroundFetch.finish(taskId);
  }
}