import 'dart:async';
import 'dart:convert';

import 'package:get/get.dart';
import 'package:vitalapp/pages/redirect/redirect.dart';
import 'package:vitalapp/routes/nav_ids.dart';
import 'package:vitalapp/routes/routes.dart';

abstract class NavGotoHelper {
  static Timer? _timer;

  static void goto(String name, [Map? patientInfo]) {
    print("❤goto: $name");
    if (_timer != null) {
      _timer!.cancel();
      _timer = null;
    }

    _timer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
      _check(name, patientInfo);
    });
  }

  static void _check(String name, [Map? patientInfo]) {
    if (RedirectPage.isBusy) {
      return;
    }

    _timer!.cancel();
    _timer = null;

    print("GOTO $name");
    Routes.parameters["name"] = name;
    if (patientInfo != null) {
      Routes.parameters["patientInfo"] = jsonEncode(patientInfo);
    } else {
      Routes.parameters["patientInfo"] = null;
    }
    Get.offNamed('/redirect', id: NavIds.HOME);
  }
}
