import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fcs/data/services/services.dart';
import 'package:fcs/domain/constants.dart';
import 'package:fcs/domain/entities/user.dart';
import 'package:fcs/pages/main/model/base_model.dart';
import 'package:logging/logging.dart';

class CustomerModel extends BaseModel {
  final log = Logger('CustomerModel');

  List<User> customers = [];
  List<User> invitations = [];
  StreamSubscription<QuerySnapshot> customerListener;
  StreamSubscription<QuerySnapshot> invitationListener;

  @override
  void privilegeChanged() {
    super.privilegeChanged();
    _loadCustomer();
    _loadInvitations();
  }

  @override
  logout() async {
    if (customerListener != null) customerListener.cancel();
    if (invitationListener != null) invitationListener.cancel();
    customers = [];
    invitations = [];
  }

  Future<void> inviteUser(String userName, String phoneNumber) {
    return Services.instance.userService.inviteUser(userName, phoneNumber);
  }

  Future<void> deleteInvite(String phoneNumber) {
    return Services.instance.userService.deleteInvite(phoneNumber);
  }

  Future<void> acceptRequest(String userID) {
    return Services.instance.userService.acceptRequest(userID);
  }

  Future<void> _loadCustomer() async {
    if (user == null || !user.hasCustomers()) return;

    try {
      if (customerListener != null) customerListener.cancel();

      customerListener = Firestore.instance
          .collection("/$user_collection")
          .where("is_sys_admin", isEqualTo: false)
          .orderBy("message_time", descending: true)
          .snapshots()
          .listen((QuerySnapshot snapshot) {
        customers.clear();
        customers = snapshot.documents.map((documentSnapshot) {
          var user =
              User.fromMap(documentSnapshot.data, documentSnapshot.documentID);
          return user;
        }).toList();
        notifyListeners();
      });
    } catch (e) {
      log.warning("error:$e");
    }
  }

  Future<void> _loadInvitations() async {
    if (user == null || !user.hasCustomers()) return;

    try {
      if (invitationListener != null) invitationListener.cancel();

      invitationListener = Firestore.instance
          .collection("/$invitations_collection")
          .snapshots()
          .listen((QuerySnapshot snapshot) {
        invitations.clear();
        invitations = snapshot.documents.map((documentSnapshot) {
          var user =
              User.fromMap(documentSnapshot.data, documentSnapshot.documentID);
          return user;
        }).toList();
        notifyListeners();
      });
    } catch (e) {
      log.warning("error:$e");
    }
  }

  Future<User> getUser(String id) async {
    String path = "/$user_collection";
    var snap = await Firestore.instance.collection(path).document(id).get();
    return User.fromMap(snap.data, snap.documentID);
  }

  Future<List<User>> getInvoiceUsers(String fcsShipmentID) async {
    List<User> users = [];
    try {
      var snaps = await Firestore.instance
          .collection(
              "/$fcs_shipment_collection/$fcsShipmentID/$user_collection")
          .where("pending_invoice_carton_count", isGreaterThan: 0)
          .getDocuments(source: Source.server);
      users = snaps.documents.map((documentSnapshot) {
        var user =
            User.fromMap(documentSnapshot.data, documentSnapshot.documentID);
        return user;
      }).toList();
    } catch (e) {
      log.warning("Error!! $e");
    }
    return users;
  }

  Future<void> enableUser(User user, bool enabled) {
    return Services.instance.userService.enableUser(user.id, enabled);
  }
}
