prepareLocationDataAndSend method

Future<void> prepareLocationDataAndSend(
  1. String receiver,
  2. LocationDataModel locationData,
  3. LatLng? myLocation
)

Prepares location data and sends it to the specified receiver

Implementation

Future<void> prepareLocationDataAndSend(String receiver,
    LocationDataModel locationData, LatLng? myLocation) async {
  //// don't send anything to logged in atsign
  if (compareAtSign(
      receiver, AtClientManager.getInstance().atClient.getCurrentAtSign()!)) {
    return;
  }

  var isSend = false;

  for (var locData in locationData.locationSharingFor.entries) {
    if (locData.value.to == null ||
        DateTime.now().isBefore(locData.value.to!)) {
      isSend = true;
      break;
    }
  }

  //// Enhancement: Send location to only those whose from and to is between DateTime.now()
  // for (var field in locationData.locationSharingFor.entries) {
  //   if ((field.value.from == null) && (field.value.to == null)) {
  //     isSend = true;
  //     break;
  //   }

  //   if (field.value.from != null) {
  //     isSend = true;
  //     if (DateTime.now().isBefore(field.value.from!)) {
  //       isSend = false;
  //     }
  //   }
  // }

  if (isSend) {
    var atKey = newAtKey(
        5000, '$locationKey-${receiver.replaceAll('@', '')}', receiver,
        ttl: null);

    locationData.lat = myLocation?.latitude;
    locationData.long = myLocation?.longitude;

    locationData.lastUpdatedAt = DateTime.now();

    if (!masterSwitchState) {
      locationData.lat = null;
      locationData.long = null;
    }

    //// Enhancement: Uncomment if latLng should be null
    // bool _isSharingLocation = false;
    // locationData.locationSharingFor.forEach((key, value) {
    //   if ((_isSharingLocation) && (value.isSharing)) {
    //     _isSharingLocation = true;
    //   }
    // });

    // if (!_isSharingLocation) {
    //   locationData.lat = null;
    //   locationData.long = null;
    // }

    try {
      var _res = await NotifyAndPut().notifyAndPut(
          atKey, jsonEncode(locationData.toJson()),
          saveDataIfUndelivered: true);

      if (_res) {
        allAtsignsLocationData[receiver] =
            locationData; // update the map if successfully sent
      }
      _logger.finer('send loc data : $_res');
    } catch (e) {
      _logger.severe('error in sending location: $e');
    }
  }
}