import 'dart:convert';

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

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

  Future<void> createPackages(List<Package> packages, String fcsID) async {
    List<Map<String, dynamic>> json = packages.map((e) => e.toJson()).toList();
    return await requestAPI("/packages", "POST",
        payload: {"packages": json, "fcs_id": fcsID}, token: await getToken());
  }

  Future<void> createReceiving(Package package) async {
    return await requestAPI("/receiving", "POST",
        payload: package.toJson(), token: await getToken());
  }

  Future<void> updateReceiving(Package package) async {
    return await requestAPI("/receiving", "PUT",
        payload: package.toJson(), token: await getToken());
  }

  Future<void> deleteReceiving(Package package) async {
    return await requestAPI("/receiving", "DELETE",
        payload: {"id": package.id}, token: await getToken());
  }

  Future<void> updateProcessing(Package package) async {
    return await requestAPI("/processing", "PUT",
        payload: package.toJson(), token: await getToken());
  }

  Future<void> deleteProcessing(Package package) async {
    return await requestAPI("/processing", "DELETE",
        payload: {"id": package.id}, token: await getToken());
  }

  Future<void> changeDeliveryAddress(
      String packageID, String deliveryID) async {
    return await requestAPI("/packages/change_delivery_address", "PUT",
        payload: {"package_id": packageID, "deliver_address_id": deliveryID},
        token: await getToken());
  }

  Future<void> packageReturn(String packageID) async {
    return await requestAPI("/packages/return", "PUT",
        payload: {
          "id": packageID,
        },
        token: await getToken());
  }

  Future<List<Package>> searchPackage(String term) async {
    if (term == null || term == '') return List();

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

    int limit = 20;
    List<Package> packages = [];

    try {
      var data = await requestAPI(
          "/api/fts/$packages_collection/$escapePackage/$limit", "GET",
          url: Config.instance.reportURL, token: await getToken());

      if (data == null) return List();

      data.forEach((p) {
        var package = Package.fromJson(p);
        packages.add(package);
      });
    } catch (e) {
      log.warning("buyer error:" + e.toString());
      return null;
    }
    return packages;
  }
}
