import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fcs/data/services/services.dart';
import 'package:fcs/domain/vo/delivery_address.dart';
import 'package:fcs/pages/main/model/base_model.dart';
import 'package:fcs/domain/constants.dart';
import 'package:logging/logging.dart';

class DeliveryAddressModel extends BaseModel {
  final log = Logger('FcsShipmentModel');
  List<DeliveryAddress> deliveryAddresses = [];

  StreamSubscription<QuerySnapshot> listener;

  DeliveryAddress get defalutAddress =>
      deliveryAddresses.firstWhere((e) => e.isDefault, orElse: () => null);

  DeliveryAddress getLocalDeliveryAddress(String id) =>
      deliveryAddresses.firstWhere((e) => e.id == id, orElse: () => null);

  @override
  void privilegeChanged() {
    super.privilegeChanged();
    _loadDeliveryAddresses();
  }

  @override
  logout() async {
    if (listener != null) await listener.cancel();
    deliveryAddresses = [];
  }

  Future<void> _loadDeliveryAddresses() async {
    if (user == null) return;
    String path = "$delivery_address_collection/";
    if (listener != null) listener.cancel();
    deliveryAddresses = [];
    try {
      listener = Firestore.instance
          .collection('users')
          .document("${user.id}")
          .collection("$path")
          .snapshots()
          .listen((QuerySnapshot snapshot) {
        deliveryAddresses.clear();
        deliveryAddresses = snapshot.documents.map((documentSnapshot) {
          var s = DeliveryAddress.fromMap(
              documentSnapshot.data, documentSnapshot.documentID);
          return s;
        }).toList();
        notifyListeners();
      });
    } catch (e) {
      log.warning("Error!! $e");
    }
  }

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

  void initUser(user) {
    super.initUser(user);
  }

  Future<void> createDeliveryAddress(DeliveryAddress deliveryAddress) {
    return Services.instance.deliveryAddressService
        .createDeliveryAddress(deliveryAddress);
  }

  Future<void> updateDeliveryAddress(DeliveryAddress deliveryAddress) {
    return Services.instance.deliveryAddressService
        .updateDeliveryAddress(deliveryAddress);
  }

  Future<void> deleteDeliveryAddress(DeliveryAddress deliveryAddress) {
    return Services.instance.deliveryAddressService
        .deleteDeliveryAddress(deliveryAddress);
  }

  Future<void> selectDefalutDeliveryAddress(DeliveryAddress deliveryAddress) {
    return Services.instance.deliveryAddressService
        .selectDefalutDeliveryAddress(deliveryAddress);
  }
}
