import 'package:app_settings/app_settings.dart';
import 'package:connectivity/connectivity.dart';
import 'package:driverapp/config/config.dart';
import 'package:driverapp/pages/setting/request_permission_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:latlong/latlong.dart';
import 'package:location/location.dart';

import 'app_shared_preferences.dart';
import 'app_toast.dart';

AppSharedPreferences sharedPref = new AppSharedPreferences();

popWithDelay({@required BuildContext context, @required num seconds, @required VoidCallback callback}){
  Navigator.of(context).pop();
  Future.delayed(Duration(milliseconds: (seconds*1000).toInt())).then((value){
    callback();
  });
}

pop(BuildContext context, VoidCallback callBack){
  Navigator.of(context).pop();
  callBack();
}

delay(int milliseconds, VoidCallback callback){
  Future.delayed(Duration(milliseconds: milliseconds)).then((value) => callback());
}

class Utils {
  ///show  custom Error Toast
  ///  [message] to show for user
  static showErrorToast([String message]) {
    String localMsg = generateContactAdminMessage();
    if (message != null) {
      localMsg = message.toString();
    }
    AppToast.showErrorToast(message: localMsg);
  }

  /// Check The Internet Connection
  static Future<bool> checkConnection() async {
    ConnectivityResult connectivityResult =
    await (Connectivity().checkConnectivity());
    if ((connectivityResult == ConnectivityResult.mobile) ||
        (connectivityResult == ConnectivityResult.wifi)) {
      return true;
    } else {
      return false;
    }
  }

  /// generate Contact Admin Message
  static generateContactAdminMessage([err]) {
    String localMsg = 'Something wrong happened, please contact the admin';
    if (err != null) {
      localMsg = localMsg + '\n \n' + err.toString();
    }
    return localMsg;
  }

  /// hides the keyboard if its already open
  static hideKeyboard(BuildContext context) {
    FocusScope.of(context).unfocus();
  }
  
  static double distanceBetween(LocationData point1, LocationData point2, LengthUnit unit){
    var distance = Distance();
    num dist = distance.as(
        unit,
        LatLng(point1.latitude,point1.longitude),
        LatLng(point2.latitude,point2.longitude)
    );
    return dist;
  }

  static possibleToGetLocation(Function(bool) completion) async{
    Location location = new Location();
    var serviceEnabled = await location.serviceEnabled();
    var hasPermission = await location.hasPermission() == PermissionStatus.granted;
    completion(serviceEnabled && hasPermission);
  }

  static Future<LocationData> getLocation() async {
    Location location = new Location();
    LocationData currentLocation;
    bool _serviceEnabled;
    PermissionStatus _permissionGranted;

    _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      try {
        _serviceEnabled = await location.requestService();
      } catch (e) {
        print(e);
      }
      if (!_serviceEnabled) {
        // Route to another page and send to him message "You have to enable location"
        Navigator.pushReplacement(
          AppGlobal.context,
          MaterialPageRoute(
            builder: (context) => RequestPermissionPage(),
          ),
        );
      }
    }

    _permissionGranted = await location.hasPermission();
    if (_permissionGranted == PermissionStatus.denied) {
      _permissionGranted = await location.requestPermission();
      if (_permissionGranted == PermissionStatus.denied) {
        // Route to another page and send to him message "You have to give Permission"
        Navigator.pushReplacement(
          AppGlobal.context,
          MaterialPageRoute(
            builder: (context) => RequestPermissionPage(),
          ),
        );
        //return _permissionGranted;
      } else if (_permissionGranted == PermissionStatus.deniedForever) {
        try {
          SystemNavigator.pop();
          AppSettings.openLocationSettings();
        } catch (e) {
          print(e);
        }
        // open setting page
      } else {
        currentLocation = await location.getLocation();
        return currentLocation;
      }
    } else if (_permissionGranted == PermissionStatus.deniedForever) {
      SystemNavigator.pop();
      AppSettings.openLocationSettings();

      // open setting page
    } else {
      currentLocation = await location.getLocation();
    }
    return currentLocation;
  }

  static formatStringToPascalCase(String name) {
    List<String> names = name.split(" ");
    List<String> formattedNamesList = [];
    names.forEach((name) {
      name = name.toLowerCase();
      name = name != "" ? name[0].toUpperCase() + name.substring(1) : "";

      formattedNamesList.add(name);
    });
    return formattedNamesList.join(' ');
  }
}

