import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fcs/domain/constants.dart';
import 'package:fcs/domain/entities/carton.dart';
import 'package:fcs/helpers/api_helper.dart';
import 'package:fcs/helpers/firebase_helper.dart';
import 'package:logging/logging.dart';

class CartonDataProvider {
  final log = Logger('CartonDataProvider');

  static final CartonDataProvider instance = CartonDataProvider._();
  CartonDataProvider._();

  Future<Carton> createCarton(Carton carton) async {
    var data = await requestAPI("/cartons", "POST",
        payload: carton.toMap(), token: await getToken());
    return Carton.fromMap(data, data['id']);
  }

  Future<void> updateCarton(Carton carton) async {
    return await requestAPI("/cartons", "PUT",
        payload: carton.toMap(), token: await getToken());
  }

  Future<void> deleteCarton(Carton carton) async {
    return await requestAPI("/cartons", "DELETE",
        payload: carton.toMap(), token: await getToken());
  }

  Future<void> deliver(Carton carton) async {
    return await requestAPI("/cartons/deliver", "PUT",
        payload: carton.toMap(), token: await getToken());
  }

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

    // var bytes = utf8.encode(term);
    // var base64Str = base64.encode(bytes);
    // HtmlEscape htmlEscape = const HtmlEscape();
    // String escapeBuyer = htmlEscape.convert(base64Str);

    try {
      String path = "/$cartons_collection";
      var querySnap = await FirebaseFirestore.instance
          .collection(path)
          .where("carton_number", isEqualTo: term)
          .where("carton_type",
              whereIn: [carton_from_packages, carton_from_cartons])
          .where("status", isEqualTo: carton_packed_status)
          .where("is_deleted", isEqualTo: false)
          .orderBy("user_name")
          .get();
      return querySnap.docs.map((e) => Carton.fromMap(e.data(), e.id)).toList();
    } catch (e) {
      log.warning("carton error:" + e.toString());
      return [];
    }
  }
}
