import 'package:amap_location_flutter_plugin/amap_location_flutter_plugin.dart';
import 'package:liftmanager/utils/toast.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationHelper {
  static LocationHelper _instance;
  AmapLocationFlutterPlugin _locationPlugin = AmapLocationFlutterPlugin();
  Function(String lat, String lng, String cityName, {String provinceName})
      _onLocationChanged;

  factory LocationHelper() {
    if (_instance == null) {
      _instance = LocationHelper._internal();
      _instance._locationPlugin.onLocationChanged().listen((event) {
        if (_instance._onLocationChanged != null) {
          var lat = event["latitude"];
          var lng = event["longitude"];
          var cityName = event['city'];
          var provinceName = event['province'];
          _instance._onLocationChanged(lat, lng, cityName,
              provinceName: provinceName);
        }
      });
    }

    return _instance;
  }

  LocationHelper._internal();

  Future<bool> requestPermission() async {
    final permissions = await PermissionHandler()
        .requestPermissions([PermissionGroup.location]);
    if (permissions[PermissionGroup.location] == PermissionStatus.granted) {
      return true;
    } else {
      toasts('需要定位权限!');
      return false;
    }
  }

  void getLocation(
      Function(String lat, String lng, String cityName)
          onLocationChanged) async {
    if (await requestPermission()) {
      _locationPlugin.startLocation();
      print('LocationHelper.getLocation ==== ');
      _onLocationChanged = onLocationChanged;
    }
  }

  stopGettingLocation() {
    _locationPlugin.stopLocation();
  }

  // destroyPlugin() {
  //   if (null != _locationPlugin) {
  //     _locationPlugin.destroy();
  //     _locationPlugin = null;
  //   }
  // }
}
