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

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:intl/date_symbol_data_local.dart';
//import 'file_manager.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';

import '../main.dart';
import 'common.dart';

//整个Flutter App的入口02
checkPermission() {
  WidgetsFlutterBinding.ensureInitialized();
  initializeDateFormatting("zh_CN", null).then((value) async {
    //整个Flutter App的入口03
    bool ret = await getPermission();
    if (ret) {
      var app = runApp(MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: new ThemeData(
            brightness: Brightness.light,
            backgroundColor: Colors.white,
            platform: TargetPlatform.android),
        home: new SplashScreen(),
        routes: <String, WidgetBuilder>{
          '/home': (BuildContext context) => MyApp()
        },
      ));
      if (Platform.isAndroid) {
        getSDCardDir().then((value) {
          app;
        });
      } else if (Platform.isIOS) {
        app;
      }
    } else {
      Fluttertoast.showToast(msg: '用户未授权，程序无法正常运行！', gravity: ToastGravity.CENTER);
      SystemChannels.platform.invokeMethod('SystemNavigator.pop');
    }
  });
}

//整个Flutter App的入口03
// Permission check，适用于 permission_handler: ^5.x.x
Future<bool> getPermission() async {
  if (Platform.isAndroid) {
    // You can request multiple permissions at once.
    Map<Permission, PermissionStatus> permissionStatuses = await [
      Permission.storage,
      Permission.camera,
      Permission.microphone,
    ].request();

    if (permissionStatuses[Permission.storage] != PermissionStatus.granted ||
        permissionStatuses[Permission.camera] != PermissionStatus.granted ||
        permissionStatuses[Permission.microphone] != PermissionStatus.granted) {
      return false;
    }
  } else if (Platform.isIOS) {}
  return true;
}

// Permission check，适用于 permission_handler: ^3.3.0
// Future<bool> getPermission() async {
//   List<PermissionGroup> permissionGroupList = [
//     PermissionGroup.storage,
//     PermissionGroup.camera,
//     PermissionGroup.microphone,
//   ];
//   if (Platform.isAndroid) {
//     PermissionStatus permission = await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
//     if (permission != PermissionStatus.granted) {
//       await PermissionHandler().requestPermissions(permissionGroupList);
//     }
//     permission = await PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
//     if (permission != PermissionStatus.granted) {
//       return false;
//     }
//   } else if (Platform.isIOS) {}
//   return true;
// }

//整个Flutter App的入口04
Future<void> getSDCardDir() async {
  Common().sDCardDir = (await getExternalStorageDirectory()).path;
}
