/*
 * Copyright (c) 2024-2025 Fabian Freund.
 *
 * This file is part of WebLibre
 * (see https://weblibre.eu).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
import 'dart:async';

import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:tor/tor.dart';

@pragma('vm:entry-point')
Future<void> onStart(ServiceInstance service) async {
  Timer? timeout;

  await Tor.init();

  final portSub = Tor.instance.events.stream.listen((port) {
    service.invoke('portUpdate', {'port': port});
  });

  Future<void> stopService() async {
    timeout?.cancel();
    timeout = null;

    Tor.instance.stop();
    service.invoke('portUpdate', {'port': -1});

    await portSub.cancel();

    await service.stopSelf();
  }

  void addHeartbeat() {
    timeout?.cancel();
    timeout = Timer(const Duration(minutes: 15), () async {
      // logger.i('Terminating tor due to timeout');
      await stopService();
    });
  }

  await Tor.instance.start();

  service.on("heartbeat").listen((event) {
    // logger.d('Received tor heartbeat');
    addHeartbeat();
  });

  service.on("sync").listen((event) {
    service.invoke('portUpdate', {'port': Tor.instance.port});
  });

  service.on("stop").listen((event) async {
    await stopService();
  });
}
