import 'package:flutter/widgets.dart';
import 'package:url_launcher/url_launcher.dart';

import '../globals.dart';
import '../models/connection.dart';
import 'snackbar_builder.dart';

Future<bool> openUrlStringInSystembrowser(
    BuildContext context, String url, String label) async {
  final uri = Uri.tryParse(url);
  if (uri == null) {
    buildSnackbar(context, 'Bad link: $url');
    return false;
  }
  if (await canLaunchUrl(uri)) {
    if (context.mounted) {
      buildSnackbar(
        context,
        'Attempting to launch $label: $url',
      );
    }

    await launchUrl(uri, mode: LaunchMode.externalApplication);
  } else {
    if (context.mounted) {
      buildSnackbar(context, 'Unable to launch $label: $url');
    }

    return false;
  }
  return true;
}

Future<void> openProfileExternal(
  BuildContext context,
  Connection connection,
) async {
  final openInBrowser =
      await showYesNoDialog(context, 'Open profile in browser?');
  if (openInBrowser == true && context.mounted) {
    await openUrlStringInSystembrowser(
        context, connection.profileUrl.toString(), 'Post');
  }
}
