import 'dart:async';

import 'package:flutter/material.dart';

import 'package:pweb/generated/i18n/app_localizations.dart';


Future<void> notifyUserX(
  BuildContext context,
  String message, {
  int delaySeconds = 3,
}) async {
  final scaffoldMessenger = ScaffoldMessenger.maybeOf(context);
  if (scaffoldMessenger != null) {
    scaffoldMessenger.showSnackBar(
      SnackBar(
        content: Text(message),
        duration: Duration(seconds: delaySeconds),
      ),
    );
    return;
  }

  await _showMessageDialog(context, message);
}

Future<void> notifyUser(
  BuildContext context,
  String message, {
  int delaySeconds = 3,
}) =>
    notifyUserX(context, message, delaySeconds: delaySeconds);

Future<void> postNotifyUser(
  BuildContext context,
  String message, {
  int delaySeconds = 3,
}) {
  final completer = Completer<void>();

  WidgetsBinding.instance.addPostFrameCallback((_) async {
    if (!context.mounted) {
      completer.complete();
      return;
    }
    await notifyUser(context, message, delaySeconds: delaySeconds);
    completer.complete();
  });

  return completer.future;
}

Future<void> _showMessageDialog(BuildContext context, String message) async {
  if (!context.mounted) return;
  final loc = AppLocalizations.of(context)!;
  await showDialog<void>(
    context: context,
    builder: (dialogContext) => AlertDialog(
      title: Text(message),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(dialogContext).pop(),
          child: Text(loc.ok),
        ),
      ],
    ),
  );
}
