import 'dart:convert';

import 'package:fcs/domain/entities/pickup.dart';
import 'package:fcs/helpers/api_helper.dart';
import 'package:fcs/helpers/firebase_helper.dart';
import 'package:logging/logging.dart';

import '../../config.dart';

class PickupDataProvider {
  final log = Logger('PickupDataProvider');
  static final PickupDataProvider instance = PickupDataProvider._();
  PickupDataProvider._();

  Future<void> completePickup(Pickup pickup) async {
    return await requestAPI("/pickups/complete", "PUT",
        payload: pickup.toMapForComplete(), token: await getToken());
  }

  Future<List<Pickup>> searchPickup(String term) async {
    if (term == null || term == '') return [];

    List<Pickup> pickups = [];

    try {
      var data = {
        "filters": [
          {
            "field": "pickup_number",
            "compare": "like",
            "value": "%" + term.toUpperCase() + "%"
          }
        ]
      };
      var result = await requestAPI("/api/data/pickups", "POST",
          token: await getToken(),
          url: Config.instance.reportURL,
          payload: jsonEncode(data));
      if (result == null) return pickups;
      result.forEach((d) {
        var package = Pickup.fromJson(d);
        pickups.add(package);
      });
    } catch (e) {
      log.warning("Error >>>>${e.toString()}");
    }
    return pickups;
  }
}
