import 'dart:async';
import 'dart:io';

import 'package:account_center/account_center.dart';
import 'package:account_center/widget/confirm_dialog.dart';
import 'package:account_center/widget/permission_util.dart';

extension PermissionExtension on Permission {
  Future<bool> requestByTipDialog(String tip) async {
    var result = Completer<bool>();
    var status = await this.status;
    if (status == PermissionStatus.granted ||
        status == PermissionStatus.limited) {
      //已经授权
      result.complete(true);
    } else {
      if (Platform.isIOS) {
        _confirmRequest(result);
      } else {
        ConfirmDialog(
          content: tip,
          confirm: () {
            _confirmRequest(result);
          },
          cancel: () {
            result.complete(false);
          },
        ).show(barrierDismissible: false);
      }
    }

    return result.future;
  }

  void _confirmRequest(Completer<bool> result) {
    request().then((value) {
      if (value == PermissionStatus.granted ||
          value == PermissionStatus.limited) {
        result.complete(true);
      } else {
        result.complete(false);
      }
    });
  }
}
