import 'dart:async';
import 'package:barcode_scan2/gen/protos/protos.pb.dart';
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: () => DeliveryAddress());

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

  @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 = FirebaseFirestore.instance
          .collection('users')
          .doc("${user!.id}")
          .collection("$path")
          .snapshots()
          .listen((QuerySnapshot snapshot) {
        deliveryAddresses.clear();
        deliveryAddresses = snapshot.docs.map((documentSnapshot) {
          var s = DeliveryAddress.fromMap(
              documentSnapshot.data() as Map<String, dynamic>,
              documentSnapshot.id);
          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 FirebaseFirestore.instance.collection(path).doc(id).get();
    return DeliveryAddress.fromMap(snap.data()!, snap.id);
  }

  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);
  }

  Future<List<DeliveryAddress>> getDeliveryAddresses(String userID) async {
    String path = "$delivery_address_collection/";
    var querySnap = await FirebaseFirestore.instance
        .collection('users')
        .doc("$userID")
        .collection("$path")
        .orderBy("full_name")
        .get();
    return querySnap.docs
        .map((e) => DeliveryAddress.fromMap(e.data(), e.id))
        .toList();
  }
}
