import 'dart:convert';

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

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

  Future<void> inviteUser(String userName, String phoneNumber) async {
    return await requestAPI("/invites", "POST",
        payload: {"user_name": userName, "phone_number": phoneNumber},
        token: await getToken());
  }

  Future<void> deleteInvite(String phoneNumber) async {
    return await requestAPI("/invites", "DELETE",
        payload: {"phone_number": phoneNumber}, token: await getToken());
  }

  Future<void> acceptRequest(String userID) async {
    return await requestAPI("/accept_request", "PUT",
        payload: {"id": userID}, token: await getToken());
  }

  Future<void> uploadMsgToken(String token) async {
    return await requestAPI("/messages/token", "POST",
        payload: {"token": token}, token: await getToken());
  }

  Future<void> removeMsgToken(String token) async {
    return await requestAPI("/messages/token", "DELETE",
        payload: {"token": token}, token: await getToken());
  }

  Future<User> findUser(String phoneNumber) async {
    QuerySnapshot querySnap = await Firestore.instance
        .collection(user_collection)
        .where("phone_number", isEqualTo: phoneNumber)
        .limit(1)
        .getDocuments();

    if (querySnap.documents.length > 0) {
      var snap = querySnap.documents.first;
      User user = User.fromMap(snap.data, snap.documentID);
      return user;
    }
    return null;
  }

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

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

    int limit = 20;
    List<User> users = [];

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

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

      data.forEach((buyer) {
        var user = User.fromJson(buyer);
        users.add(user);
      });
    } catch (e) {
      log.warning("buyer error:" + e.toString());
      return null;
    }
    return users;
  }

  Future<void> enableUser(String userID, bool enabled) async {
    return await requestAPI("/enable_user", "PUT",
        payload: {"id": userID, "enabled": enabled}, token: await getToken());
  }
}
