import 'dart:async';

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:mohem_flutter_app/classes/app_permissions.dart';
import 'package:mohem_flutter_app/classes/utils.dart';

class Location {
  static void havePermission(Function(bool) callback) {
    Geolocator.checkPermission().then((value) async {
      if (value == LocationPermission.denied || value == LocationPermission.deniedForever) {
        value = await Geolocator.requestPermission();
        callback(![LocationPermission.denied, LocationPermission.deniedForever].contains(value));
      } else {
        callback(true);
      }
    });
  }

  static void isEnabled(Function(bool) callback) {
    Geolocator.isLocationServiceEnabled().then((value) => callback(value));
  }

  static bool _listeningSettingChange = true;

  static void listenGPS({bool change = true, Function(bool)? onChange}) async {
    _listeningSettingChange = change;
    if (change == false) return;

    Future.doWhile(() async {
      await Utils.delay(1000);
      var enable = await Geolocator.isLocationServiceEnabled();
      onChange!(enable);
      return _listeningSettingChange;
    });
  }

  static void getCurrentLocation(Function(Position position, bool isMocked) callback, Function errorCallBack, BuildContext context) {
    void done(Position position) {
      //AppStorage.sp.saveLocation(position);
      bool isMocked = position.isMocked;
      callback(position, isMocked);
    }

    AppPermissions.location((granted) {
      if (granted) {
        Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.medium, timeLimit: const Duration(seconds: 10)).then((value) {
          done(value);
        }).catchError((err) {
          errorCallBack();
        });
      } else {
        // AppPermissions
      }
    }, context);
  }
}
